Adam's Lair Forum

Mouse click on overlapping GameObjects
Page 1 of 1

Author:  tufduck [ 2018/06/09, 15:03 ]
Post subject:  Mouse click on overlapping GameObjects

I'm struggling with picking the GameObject that I click on. This is my code:

public GameObject GetGameObjectAtScreenPos(Vector2 screenPos)
            GameObject gameObjHit = null;

            ShapeInfo shape = RigidBody.PickShapeGlobal(MainCamera.GetSpaceCoord(screenPos).Xy);
            if (shape != null)
                gameObjHit = shape.Parent.GameObj;
            return gameObjHit;

That works perfectly when the GameObjects are separate from each other. It even works when I scale up or rotate the GameObjects. The RigidBodies seem to scale and rotate accordingly.

But when a GameObject overlaps antoher one, that's when I'm having issues. The game object returned is not always the one on top. Sometimes the game object in the background (on the bottom) is picked. And that's not what I want.

I have tried different SpriteRenderer.Offsets, and different z-values, but that don't make a difference it seems.

So how do I solve this? Isn't the RigidBody.PickShapeGlobal-function supposed to work with GameObjects in different planes (different z-values)?

I have read and, but they don't answer my problems.

Author:  Adam [ 2018/06/10, 14:53 ]
Post subject:  Re: Mouse click on overlapping GameObjects

Hey there,

picking operations using 2D physics are always locked to the Z-0 plane and have no concept of an object "behind" or "in front of", since this dimension doesn't exist there. You can, however, write some logic manually to find the topmost object at the position. Instead of PickShapeGlobal, use the multiple-object version PickShapesGlobal, and then use the result with the highest or lowest depth value, or offset.

Author:  tufduck [ 2018/06/11, 07:51 ]
Post subject:  Re: Mouse click on overlapping GameObjects

Thats awesome, thanks!

Page 1 of 1 All times are UTC + 1 hour [ DST ]
Powered by phpBB® Forum Software © phpBB Group