- Home /
Using Camera screen point to ray for look rotation problem...
Hey there, I have been trying to solve this problem forever now. I'm trying to rotate the main camera using a ray that originates from itself with mouse position as input. Then I use that rays direction to make a look rotation for the camera, that way the camera rotates towards the current mouse position at a certain speed (using lerp as well) until its looking / pointing to the current mouse position.
Here's the code:
Ray mousePos = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 lerpToMousePos = Vector3.Lerp(transform.forward, mousePos.direction, 2 * Time.deltaTime);
transform.rotation = Quaternion.LookRotation(lerpToMousePos);
The problem occurs when I try rotating the camera +-90 degrees on the x-axis, it starts spinning like crazy. I want the camera to be able to rotate all the way around on the x-axis freely.
Here's what happens when I try to rotate the camera to more than 90 degrees on the x-axis:
https://gyazo.com/626a8b16b8e31b995966778a86a9e344
In this gif the green drawn ray in the scene just represents the cameras transform.forward / direction / current rotation. The red ray is the one coming from the camera towards the mouse current position (mousePos ray). If you know how to maybe solve this in the slightest (or know a possible alternative solution) please respond to this, I have been trying to find the cause of this for too long. Thanks for your time!
Answer by FlaSh-G · Jun 21, 2017 at 12:29 PM
Quaternion.LookRotation can take a second vector that defines where "up" is. Since you do not do that, it just takes Vector3.up, so as soon as you hit or even dangle around Vector3.up as forward vector, this can happen.
In your case, it might be enough to pass the current transform.up vector as up. Since it rotates with the object each frame, it's going to make the object's up stay as much the same as possible.
transform.rotation = Quaternion.LookRotation(lerpToMousePos, transform.up);