Look around!

Objective: Add mouse look system to the player for 3D game.

View pans left and right and tilts up and down using mouse.

To have the main camera follow the player just drag it into the player so that it becomes a child. The camera will now follow the player where ere they lead.

Player hierarchy.

The main camera is positioned just above, Y 3, and behind, Z -10, the player with a slight downward, X 15, rotation. The player begins at x 0, y 1.59, z 0.

Main Camera set up.

Create a CameraLook method on the player that handles perspective change. To enable perspective change the right mouse button must be pressed. This right mouse requirement allows the mouse to be used to select other UI components without impacting player rotation. Panning the view left and right uses mouse input to modify the player rotation. The player’s currentRotation stores the localEulerAngles. The y axis is then modified by the Mouse X input. The player’s localRotation is then set using the Quaternion.AngleAxis to avoid gimble lock. An Euler angle has three angles; however, a rotation actually has four mathematical components, i.e. the quaternion. To avoid ambiguity in a rotation a quaternion should be used to set rotation.

CameraLook() method on Player

The tilt up and down uses the mouse input to modify the main camera rotation. The currentCameraRotation stores the localEulerAngles for the main camera. The x axis of this variable is then modified by the Mouse Y input. The main camera’s localRotation is then set using the Quaternion.AngleAxis to avoid gimble lock. A localRotation must be used for the main camera to avoid complex rotational behavior in global space as the player pans left and right.

--

--

Unity Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store