Creating Player Movement (Single Player)

Checked with version: 5.3

-

Difficulty: Intermediate

The first piece of game-like functionality in this example will be to move the Player GameObject in the scene. We will do this with a new script called “PlayerController”.

To begin with the PlayerController script will be written without any Networking code so it will only work in a single-player environment.

  • Create and Add a new script named “PlayerController” to the Player prefab asset.
  • Open the script for editing.
  • Replace all of the code in the script with the following simple PlayerController class:

PlayerController

Code snippet

using UnityEngine;

public class PlayerController : MonoBehaviour
{
    void Update()
    {
        var x = Input.GetAxis("Horizontal") * Time.deltaTime * 150.0f;
        var z = Input.GetAxis("Vertical") * Time.deltaTime * 3.0f;

        transform.Rotate(0, x, 0);
        transform.Translate(0, 0, z);
    }
}

It is worth noting that the entire script above can be copied into the clipboard by using the button above the script to the upper right that looks like this:

description

This PlayerController script allows the player to control the Player GameObject.

By default, Input.GetAxis(“Horizontal”) and Input.GetAxis(“Vertical”) allow the player to use the WASD and arrow keys, a controller pad or other device to move the player. For more information, please see the page on the Input Manager.

  • Save the script.
  • Return to Unity.
  • Save the scene.

Related documentation