Skip to main content

Mouse Look

Below is a code example for how to setup a mouse look on a camera object.

speedH and speedV are the speed at which the camera will rotate horizontally and vertically.

With the default input actions a Look binding is created.

This allows us to use an OnLook function call.

As this is bound to the mouse (or right stick) a 2D vector is accepted.

This is handled in the same way that movement is for the player movement.

The difference is that this is used to change the camera viewpoint.

The camera is transformed in the Update() function.

You need to add a PlayerInput component to the Camera object.

using System.Collections; 
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class CameraScript : MonoBehaviour
{

public float speedH = 2.0f;
public float speedV = 2.0f;

private float yaw = 0.0f;
private float pitch = 0.0f;

private float movementX, movementY;

// Use this for initialization
void Start()
{

}

void OnLook(InputValue movementValue)
{
Vector2 movementVector = movementValue.Get<Vector2>();

movementX = movementVector.x;
movementY = movementVector.y;
}


// Update is called once per frame
void Update()
{

yaw += speedH * movementX;
pitch -= speedV * movementY;

transform.eulerAngles = new Vector3(pitch, yaw, 0.0f);

}
}