Search Unity

EventSystem, Physics2d Raycaster, and stacks of sprites

Discussion in '2D' started by kineticabstract, Apr 3, 2016.

  1. kineticabstract

    kineticabstract

    Joined:
    Nov 15, 2014
    Posts:
    10
    I'm using the EventSystem to detect touch on my sprites. I've implemented the IPointerDownHandler for each type of object that I want to respond to taps. All of that is fine. I don't know that it works any better than OnMouseDown(), but it is working, so I'm pretty happy with it.

    My problem is this - I want to be able to have every object in the path of the Physics2DRaycaster respond to the tap. I understand that it is currently working as advertised - the docs state that the object closest to the camera will respond to the event - but I'd like for every sprite with a 2D collider that exists at a given location at the time of a tap to respond to the event.

    Is there a way to make this happen? Or do I need to re-work all of my code so that I do my own raycasting on a tap, and generate a signal to every object in its path? I'm pretty sure that I can do this with Physics2D.RaycastAll, but I'd prefer to just use the EventSystem if it is possible.
     
  2. kineticabstract

    kineticabstract

    Joined:
    Nov 15, 2014
    Posts:
    10
    In case anyone else is trying to accomplish the same thing - barring someone point out an EvenSystem function that would suit the bill, I've implemented the following work-around:

    My sprites implement the IPointerDownHandler interface, and the first one to receive OnPointerDown calls the following code:


    int layerMask = 1 << 8;
    RaycastHit2D[] hits = Physics2D.RaycastAll(transform.position, Vector2.zero, 0.0f, layerMask);
    foreach (RaycastHit2D hit in hits)
    {
    Bouncer currentBouncer = hit.transform.GetComponent<Bouncer>();
    if (currentBouncer != null)
    {
    currentBouncer.BeenTapped();
    }
    }

    ...which propagates the original taps among the other sprites in the same location, as long as they all match my layer mask. This only works because the 2D version of RaycastAll captures the collider(s) in which it originates, unlike the 3D version.