Unity Development — Camera Mouse

We have looked at many ways to move our characters in 2D, 3D, and even 2.5D. In a 3D world, however, we have not yet allowed the player to look around on their own. How about we add that control right now?

To start out with, we should have a Player of some sort ground for them to stand on. While there are other ways to have the Main Camera follow the Player, with the use of Cinemachine, we are going to use a classic method and make it a child of the Player itself.

Afterward, we are going to move the Main Camera, so that it correctly lines up our Player avatar the way we like on the screen. This is determined by your favorite 3rd person games. Zelda, Fortnite, Gears of War. Place it however you feel comfortable.

Now we are going to have the mouse move the camera. This is somewhat similar to moving the Player itself. We are going to grab inputs to represent each axis, but this time, they will be mouse inputs and they will move a rotation of the camera, instead of moving positions.

You can also add a global float variable to change the mouse sensitivity. This is common practice for 3rd person shooters.

Like the specific x or y of a transform.position, you cannot simply change the rotation of an axis with transform.rotation.y = 5.0f, or something of that nature. So instead, we are going to make a Vector3 variable, make changes to that, and then assign our new rotation to that Vector3.

Notice in the last line, we are changing the localRotation, as opposed to just rotation. This is because the Main Camera is a child of Player and so the global rotation would move many more things and make it a mess, rather than simply moving the localRotation, for the Camera only.

Also, Quaternion.AngleAxis() takes the rotation value we want (which we have set to currentRotation.y) and sets it to a specific axis (which for us would he around the Y axis, so Vector3.up works just fine). We do the same thing for the X-axis and put it all together for a camera movement function.

The last part is to make sure that the cursor does not interrupt the game. In the Start() or Awake() function, we are going to add some built in code, to make sure it is locked in place and invisible.

In the Update(), you may also add input to get out of the locked state.

Play around with the mouse sensitivity and locks and make your camera movement smooth as silk.