Local control for Player

Hal Brooks
3 min readDec 2, 2021

Objective: Allow player to move based on local camera perspective.

The main camera is a child of the Player game object, to allow it to follow the player as they move. The Player script attached to the this game object has the variables shown below. A character controller component is used to move the player, thus a reference to the _controller is assigned in void Start(). Other variables will be discussed as they are implemented.

Variables required for control of the Player.

A Movement() method for the Player script is shown below. The Movement() method uses two private variables _isGrounded to capture the Physics.Raycast bool response to detect the ground within _groundDetect float distance. If the player _isGrounded the private Vector3 _velocity is used to calculate player movement, using user input and the _speed float variable. The player can jump on pressing the space key if _isGrounded is true. Finally _controller.Move() actually moves the player’s position. The _velocity is multiplied by the time step to determine distance moved.

Movement method using global axes.

The above method moves the Player along the x and z axis within Unity. However, when we add a camera to provide local perspective the movement is not relative to the players point of view, see below. The Player is using the global x, y, and z positions. When the A and D key is pressed the player moves left and right on the global x axis. This movement uses the global perspective. The user wants to move left and right relative to their forward view. Movement along the global axes is not intuitive from player’s perspective. The global axes are usually unknown to the player.

Pressing the A and D keys only, the global player moves on the global x axis, regardless of perspective.

The Movement() method below is more intuitive for the player. By changing the verticalIn to use transform.forward to modify the _velocity and horizontalIn to use transform.right to modify the _velocity along with _speed, shown below, the input is now changed to a local perspective.

The same A and D keys now move left and right based upon the local perspective, below. Initially along the x axis, but after rotation of the camera view the same keys move along the z axis, i.e. left and right for the player. This movement uses the local perspective.

Pressing the A and D keys only, the player moves left and right relative to the camera’s perspective.

The concept of global vs local position and perspective is important in Unity. For a developer the global scale is useful to place objects throughout the game, but the player cares most about their local perspective. Movement is far more intuitive to the user using a local system than the abstract global axes used by the developer.

--

--