2D Raycast in z Direction

Hey Unity Community,

I am developing a 2D top down game where the hero should move to the mouse click location. The thing is that there will be other clickable elements in the scene like collectables or other players. If these are clicked, the player should not move to them but select them.
I am sorting the Layers (like Background, collectables, enemies) with the z axis.
Now I wanna do a raycast on the z axis that detects what on the screen is clicked (e.g. moving plane, enemy, collectable) and execute different actions depending on the collider tag.
Now my question: How do I properly cast a Ray on the z axis in a 2D game, or is there an even better way to handle that?

Check the picture to see what I mean.

Thanks for your help :slight_smile:

1 Like

There’s pseudo 3D raycast calls here. Note it’s much more efficient to use 2D overlap point calls here.

3 Likes

How do I use those overlap point calls to find the first object that gets hit by the mouse click?

You have to sort the results by Transform.position.z yourself which is what the RayIntersection does. Note that physics has no idea about rendering order so nothing will give you that via physics queries.

According to the The OverlapPointAll documentation: “The colliders in the returned array are sorted in order of increasing Z coordinate. An empty array is returned if there are no colliders over the point.” Which means the colliders have no need to be sorted, if I am correct? If that is the case, then colliders[0] should be the first hit object.

Thank you for your help :slight_smile:

Yes, that’s true. I was assuming you meant via your own rendering order relative to that position.

1 Like

It works! Thank you :slight_smile: #Closerequest

1 Like