Rotate Character with Mouse

Character Rotation using the Mouse

Yesterday, you saw how you can implement character movement using WASD keys. However, probably you have noticed you cannot rotate your character. On the other hand, in AAA games usually you can change the orientation of the character using the mouse movement. Let's try and implement it too.

    1. We need the mouse position.  

float mouseX = Input.GetAxis("Mouse X");
float mouseY = -Input.GetAxis("Mouse Y");

       You probably have noticed that we get the position of the mouse on X, but on Y we inverse the sign of the mouse position. Why do you think we do this? Think about it! In a computer game, when you move the mouse to the left, how does the character move? It moves to the right. But when you move the mouse up, does the character look down? No! It looks up.
 
    2. We compute the new angles for the orientation based on the mouse position.   
void Start()
{
    rotX = transform.localRotation.eulerAngles.x; // initial orientation
    rotY = transform.localRotation.eulerAngles.y; // initial orientation
}

void Update()
{
    rotY += mouseX * mouseSensitivity * Time.deltaTime;
    rotX += mouseY * mouseSensitivity * Time.deltaTime;
}

    3. We make sure we don't rotate too much. We use function Mathf.Clamp(float value, float min, float max), which restricts the value of value to be inside the range defined by min and max values.
Mathf.Clamp(rotX, -clampAngle, clampAngle);
    4. We apply the new rotation.  
Quaternion localRotation = Quaternion.Euler(rotX, rotY, 0.0f);
transform.rotation = localRotation;
The final solution should look like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraSwitch: MonoBehaviour
{
    float rotX = 0.0f;
    float rotY = 0.0f;
    
    float mouseSensitivity = 100.0f;
    float clampAngle = 80.0f;
    
    void Start()
    {
    	rotX = transform.localRotation.eulerAngles.x;
        rotY = transform.localRotation.eulerAngles.y;
    }
    
    void Update()
    {
    	float mouseX = Input.GetAxis("Mouse X");
        float mouseY = -Input.GetAxis("Mouse Y");
        
        rotY += mouseX * mouseSensitivity * Time.deltaTime;
        rotX += mouseY * mouseSensitivity * Time.deltaTime;
        rotX = Mathf.Clamp(rotX, -clampAngle, clampAngle);
        
        Quaternion localRotation = Quaternion.Euler(rotX, rotY, 0.0f);
        transform.rotation = localRotation;
    }
}
Last modified: Saturday, 24 July 2021, 5:16 PM