Reputation: 97
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);
}
}
Upvotes: 5
Views: 9868
Reputation: 1224
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.
Upvotes: 0
Reputation: 26
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));
Upvotes: 0
Reputation: 38
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);
Upvotes: 0