When playing a shooter game, no matter it is a 1st person or 3rd person, they all need mouse to control the camera look direction.
In this article, we will create a camera look system controlling by mouse.
To move the camera by using mouse, we need to finish the following steps in order:
- Get the mouse input
- Make sure the target controlling axis.
- Set the input detecting function to control the camera
With these, now we can start creating this camera controlling system.
To find out the mouse input in Unity, open Project Settings from the drop down menu, then select Input Manager.
In here we can see the name of these 2 input function:
“Mouse X” & “Mouse Y”.
The next is checking the axis that we are going to control.
Axis of Player and camera
First let’s rotate the Player to left and right. Inside Update(), let’s store the mouse input value as float.
To turn left and turn right, means we will need to rotate the Y-axis of Player. And the mouse movement would be left and right, which means moving the value on X-axis.
Use these value in code to make it rotatable.
These lines of code would make the Player rotating by mouse movement on X-axis. In these lines, we use a function called “Quaternion.AngleAxis”, which was used to rotate an object with an angle and an axis value.
Then we need to rotate the Camera.
Before we locate the rotation data of camera, we need to create a variable to store the camera.
Once we got the reference of camera, we can control it with mouse.
Please notice that these 2 rotation must rotate in local space, and the reason had been explained in the previous article.
Once done, we have a functional camera looking system!