'Raycast from Camera to Mouse Position in Game World
When the mouse is at the Door (red area) i want to do something. I am trying to cast a Ray but the Ray doesn't hit the Door and i cant find where exactly it is hitting. Also how can i Debug.DrawRay this ray?
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, Mathf.Infinity))
{
if (hit.collider.tag == "InteractiveDoor")
{
doorInteractGameObject.SetActive(true);
}
else
{
doorInteractGameObject.SetActive(false);
}
}
Solution 1:[1]
You might need to create a LayerMask and add it to the parameters for Physics.Raycast; also make sure that the door has a collider on it. You would be surprised how many times I just forgot to add a collider.
In terms of drawing the ray in case this is not working for some reason. Use Debug.DrawRay. I recommend putting it in FixedUpdate() or Update(). Color and duration you can set to whatever you want but I recommend having depthTest be false since you want the ray to be drawn regardless. Then call it like:
Debug.DrawRay(ray.origin, ray.direction, <color>, <duration>, false);
Solution 2:[2]
You can draw this ray as:
Debug.DrawRay(ray.origin, ray.direction);
or
Debug.DrawRay(Camera.main.transform.position, Camera.main.ScreenPointToRay(Input.mousePosition).direction);
Option 1 is more direct once you've defined your ray, but option 2 gives you more choice to play around if it turns out this Ray doesn't behave the way you expect it to.
camera.ScreenPointToRay expects a Vector3 but Input.mousePosition returns a Vector2. The Unity docs on Vector3 and Vector2 appear that you should be able to use Vector2 as Vector3 implicitely and it'll populate the z component as 0, but if the Debug.DrawRay shows that the ray is the issue, then you need to append a 0. Maybe something like:
Ray ray = Camera.main.ScreenPointToRay(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));
Solution 3:[3]
The fix is to go to your camera and set the tag to 'MainCamera'. Or you can modify your code to have a camera variable and use that variable instead of Camera.main.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | elveskevtar |
| Solution 2 | |
| Solution 3 | Gurbela |

