Rotating camera using mouse by C# script in unity

 Here is an example script which you can attach to camera object in order to rotate it by using mouse and make camera child of your character gameObject:

Code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraMouseLook : MonoBehaviour
{
    public float sensitivity = 100.0f;
    public float smoothing = 2.0f;
    Vector2 mouseLook;
    Vector2 smoothV;
    GameObject character;

    void Start()
    {
        character = this.transform.parent.gameObject;
    }

    void Update()
    {
        var md = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
        md = Vector2.Scale(md, new Vector2(sensitivity * smoothing, sensitivity * smoothing));
        smoothV.x = Mathf.Lerp(smoothV.x, md.x, 1f / smoothing);
        smoothV.y = Mathf.Lerp(smoothV.y, md.y, 1f / smoothing);
        mouseLook += smoothV;
        mouseLook.y = Mathf.Clamp(mouseLook.y, -90f, 90f);
        transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);
        character.transform.localRotation = Quaternion.AngleAxis(mouseLook.x, character.transform.up);
    }
}

We uses Input.GetAxisRaw() method in this example code for getting horizontal and vertical movement of mouse and then we update camera rotation according to these values. You can also adjust smoothness and sensitivity of camera by adjusting sensitivity and smoothing variables according to you.

Rotating camera using mouse


We uses Quaternion.AngleAxis( method for setting camera rotation according to mouse movement and above code will also allow you to limit camera axis on y-axis so that camera will not flip.

In this example we make camera child object of other object so when our mouse move then it also update its parent rotation. You can modify this script according to your need. There are also many ways of doing this.


Comments