- Home /
[2D] Raycast to mouse cursor = offset on Y axis
Hello everyone,
I am trying to learn using raycasts for checking if someone clicks on a 2D sprite object with the mouse and I stumbled upon a really weird little thing: I need to click a certain distance below a clickable sprite in order to click on it.
Say, if you have a rectangle sprite with a 2D box collider, clicking on the rectangle image doesn't yield a hit. Moving the mouse cursor a small distance below the rectangle and clicking in 'empty air' reacts as if you clicked on the collider object. So somehow, the 'hit-detection' between the mouse cursor and the clickable sprite has become shifted on the Y-axis.
I have absolutely no clue how this is possible. And I checked to see if the box collider of the rectangle happens to be offset on the sprite image, but it isn't. Does anyone have a clue on what might be going on? I did try searching for earlier threads on this but couldn't really find anything, or only found problems with no answers.
Could someone explain why this is happening... and how to solve it? My unity is version 4.3.3f1, if that has something to do with it. I'll be trying to find a solution... but this really got me stuck.
The code I use:
void Update ()
{
if (Input.GetMouseButtonDown (0)) {
RaycastHit2D hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint (Input.mousePosition), Vector2.zero);
if (hit.collider != null) {
print ("object clicked: " + hit.collider);
print ("object tag: " + hit.collider.tag);
}
if(hit.collider.CompareTag("Exiter")) {
print ("Exit the game please!");
Application.Quit ();
}
}
}
I have a guess. This calculation:
Camera.main.ScreenToWorldPoint (Input.mousePosition)
...will only work if the camera is Orthographic. It will not work correctly for a Perspective camera. If you are using a perspective camera, you need to pass a distance in front of the camera as the 'z' component of the vector you pass to ScreenToWorldPoint(). And even this will only work if the rotation of your camera is (0,0,0).
I checked the main camera in the inspector windows (since the main camera is being used for this and there are no other cameras). The position and rotation transforms are all set to 0 and the projection is set to Orthographic, not Perspective...
The depth setting in the camera settings was -1, but changing that doesn't seem to make a difference.