Lorry Laurence mcLarry
Lorry Laurence mcLarry

Reputation: 394

How to convert the bounds of a box to screen coordinates

I have a 2D unity project. I cannot depend on OnMouseExit because overlapping 2D box colliders cause the method to trigger even when the mouse is inside the bounds, since something else is in front (which is not my intention).

I was going to manually check for the mouse exiting on every frame by using:

if(!_collider.bounds.contains(Input.MousePosition))

But this does not work because `mouse position' is in terms of the number of pixels across the screen, and 'bounds' is in terms of "units" relative to the origin of the scene. The camera is Orthographic and slides around to look at the 2D plane that the world's sprites sit on. I have no idea how many "units" fit across the screen and suspect that it would change as soon as you change the aspect ratio or screen size.

Upvotes: 3

Views: 815

Answers (1)

Roberto
Roberto

Reputation: 11933

You can use ScreenToWorldPoint(), to convert from screen point to 3D/2D point based on the camera's viewport, something like this:

if(!_collider.bounds.contains(Camera.main.ScreenToWorldPoint(Input.MousePosition)))

Upvotes: 2

Related Questions