- Home /
How to project the mouse cursor into 3D space for LookAt?
I've been trying to project the mouse cursor into the 3D space so I can have a character LookAt it but my first attempts haven't been the most effective.
First I tried using the method in the LookAtMouse Unity Wiki (here) but that only works in a fixed perspective camera. I'm making a third-person game, camera behind player. Then I tried just casting a ray into the world and using the hit point as the LookAt target with this script:
RaycastHit hit;
if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit)){
transform.LookAt(hit.point);
}
Which works, but only if the raycast is hitting a collider. Otherwise, if the mouse cursor is over empty space (skybox, etc.) the character will not look at the mouse. Anyone have any suggestions for what I'm trying to do?
Answer by robertbu · Jun 20, 2014 at 07:07 PM
This can be handled in a number of ways, but the right solution will highly depend on your game. Since the above code works like you want except when there is no collider, you can do it this way:
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit)) {
transform.LookAt(hit.point);
}
else {
transform.LookAt(ray.origin + ray.direction * someDist);
}
Where 'someDist' is a distance in front of the camera to project the point you want look at. FYI: not that it should make much difference, but a Ray constructed from ScreenPointtoRay() will start at the near clip plane of the camera, not at the camera position.