mouse look unity code example
Example 1: unity player look at mouse
private void Update()
{
Vector3 mousePos = Input.mousePosition;
mousePos.z = 5.23f;
Vector3 objectPos = UnityEngine.Camera.main.WorldToScreenPoint(transform.position);
mousePos.x = mousePos.x - objectPos.x;
mousePos.y = mousePos.y - objectPos.y;
float angle = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle - 90));
}
Example 2: mouselook script unity
public float lookSpeed = 3;
private Vector2 rotation = Vector2.zero;
public void Look()
{
rotation.y += Input.GetAxis("Mouse X");
rotation.x += -Input.GetAxis("Mouse Y");
rotation.x = Mathf.Clamp(rotation.x, -15f, 15f);
transform.eulerAngles = new Vector2(0,rotation.y) * lookSpeed;
Camera.main.transform.localRotation = Quaternion.Euler(rotation.x * lookSpeed, 0, 0);
}
Example 3: how to look around with mouse in unity
public class CameraController : MonoBehaviour
{
Vector2 rotation = Vector2.zero;
public float speed = 3;
void Update ()
{
rotation.y += Input.GetAxis("Mouse X");
rotation.x += -Input.GetAxis("Mouse Y");
transform.eulerAngles = (Vector2)rotation * speed;
}
}