ScreenToViewportPoint(Input.mousePosition) to Rotate Object Requires Cursor to Rotate around (0, 0) of Viewport
Greetings, I am somewhat a beginner with Unity, and I don't really know how to explain this concisely, hence the title being verbose. Here's what I'm having some difficulty with.
I have written (and partly copied from a video) a C# script attached to a moving player (which moves with WASD) that makes it rotate in the direction of the cursor:
public class LookAtMouse : MonoBehaviour
{
public Rigidbody rb;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void FixedUpdate ()
{
Vector3 mousePosition = Camera.main.ScreenToViewportPoint(Input.mousePosition);
float mouseX = mousePosition.normalized.x;
float mouseY = mousePosition.normalized.y;
float angle = 90 + Mathf.Atan2(-mouseY, -mouseX) * (Mathf.Rad2Deg);
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
When I test play the game, the object rotates with the cursor as expected, but I have to rotate it around (0, 0) of the camera viewport to fully rotate the player and not in the camera screen center where the player is, which is not expected.
I need help to set this "origin of rotation" for the mouse at the center of the screen, if that makes sense.
I used ScreenToViewportPoint because it is relative to the camera, and so camera movement doesn't affect rotation speed the farther the displacement from start.
Here is the working following camera script attached to the camera, if it's needed:
public class CameraSmoothFollow : MonoBehaviour
{
public float damp;
public GameObject player;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void FixedUpdate ()
{
Vector3 thisPosition = transform.position;
thisPosition.x = Mathf.Lerp(transform.position.x, player.transform.position.x, damp);
thisPosition.y = Mathf.Lerp(transform.position.y, player.transform.position.y, damp);
thisPosition.z = -1f;
transform.position = thisPosition;
}
}
Hopefully this is an easy fix, I appreciate your help.