I am building a 2D platformer (sort of). Default Unity setup, looking down the Z axis. I need to do two different things with detecting the mouse position.
- Player can interact with the item he’s pointing at with the mouse (both in world, and in UI).
- A UI feature needs to show a tooltip when the mouse is over certain items.
All my objects in game world are at z = 0. My canvas was at z = -5, but I’ve moved that to 0 too now. My camera is at z = -10. My camera follows the player in X and Y axes.
I have tried three approaches to this:
Vector3 mousePosition = cam.ScreenToWorldPoint(Input.mousePosition);
mousePosition.z = -10;
RaycastHit2D hit2 = Physics2D.Raycast(cam.transform.position, mousePosition - cam.transform.position, 500, mouseInteract);
if (hit2.collider != null)
{
mouseObject = hit2.transform;
} else
{
mouseObject = null;
}
The “2D” approach assumes all co-ordinates are at z=0, so instead of casting a ray from the camera, it casts from the player (which is at the same X/Y, but at z=0). This means the player can only interact with the items closest to him (which might work, but it’s not what I’m trying to do right now). It also never collides with anything in the UI layer. (the layerMask does include the UI layer).
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
{
//Debug.Log(hit.transform.gameObject.name);
mouseObject2 = hit.transform;
} else
{
mouseObject2 = null;
}
RaycastHit hit3;
if (Physics.Raycast(cam.transform.position, mousePosition - cam.transform.position, out hit3, 500, mouseInteract))
{
mouseObject3 = hit3.transform;
} else
{
mouseObject3 = null;
}
These two different 3D approaches never detect anything. Neither the UI nor the gameObjects in world.
I’m not sure if there’s a way to use the 2D physics to do this, as Unity is still 3D, as much as it would like to think it isn’t when you’re in 2D mode. But I am totally at a loss as to why the 3D raycasts aren’t picking up anything at all.
I have tried setting “mousePosition.z = -10;” to 0, 10, -10, 5, -5. None of those changed anything.
I’m sure someone is going to point out the obvious problem in less time than it took me to type all this…
Thanks in advance!