Simple Player Movement in Unity

by Lance Gold

The Unity component architecture allows for a multitude of user input options.

Return to index

From the Unity project, browse the Edit drop down menu for Project Settings, and then ‘Input Manager’.

Input Manager under Edit and Project Manager

Input Manager under Edit and Project Manager

Expanding the ‘Axes’ drop-down menu lists several categories of input. Here is the expansion of the ‘Horizontal’:

Horizontal inputs

Horizontal inputs

Testing input with code

public float horizontalInput; ... void Update() { horizontalInput = Input.GetAxis("Horizontal"); }

The added variable appears in the Unity Inspector with a float value changing during a game run, either the left, right arrow, ‘a’, ‘d’ keys.

Declaring an input variable inside the Update loop

‘HorizontalInput’ can connect with ‘_speed’ to change the ‘Vector3’ location and transform.Translate() the Player object.

[SerializeField] private float _speed = 3.5f; ... void Update() { float horizontalInput = Input.GetAxis("Horizontal"); transform.Translate(Vector3.right * horizontalInput * _speed * Time.deltaTime); }

Local variables and member functions()

The following code generates an error:

Vector3 position = Vector3(horizontalInput, verticalInput, 0); error CS1955: Non-invocable member 'Vector3' cannot be used like a method.

Prefixing the ‘Vector3’ with a ‘new’ tells the compiler this is a variable and not a method.

Vector3 position = new Vector3(horizontalInput, 0, 0);