3D Endless Runner in Unity – Player Movement

Tutorial for beginners!

Have you ever wondered how to make an amazing Endless Runner in Unity? This tutorial has everything you need!

How to make an Endless Runner in the easiest way? This video is the right explanation!


Click the video to watch.

Introduction

There is not too much to explain because the scripts are the most important part of the video. 80% of the video has scripts and the engine part for the endless runner in Unity is not much important. The codes that this game uses are in this post.

Player Movement

endless runner unity

First, the player is controlled with AddForce. That force belongs to rigidbody. The force can be X, Y and Z axis oriented and in this case, Z will be the axis of constant player movement. Other axes will be for direction movement.

Direction Movement

Second, the New Input System needs some specific actions: Left key and Right key movement. These actions are based on how the player presses the arrow keys or A and D keys.

Unlike old input system, this system needs to use InputSystem.Layer.Action.performed syntax for defining input actions. Therefore, no Input.GetKey or Input.GetButton equivalent can be part of an if-statement in new input system. Finally, the actions should look like this:

void OnLeftKeyPressed(InputAction.CallbackContext ctx)
    {
        rb.AddForce(-directionForce, 0, 0);
    }

    void OnRightKeyPressed(InputAction.CallbackContext ctx)
    {
        rb.AddForce(directionForce, 0, 0);
    }

The scripts are here:

Respawn Script

This script hasn’t been explained, simply because it is reserved for the next tutorial. There is an object tagged Platform and it reverts the player to the start position.

public float threshold;
    public Vector3 position;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if(transform.position.y < threshold)
        {
            transform.position = new Vector3(position.x, position.y, position.z);
        }
    }

    void OnTriggerEnter(Collider other)
    {
        if(other.gameObject.tag == "Platform")
        {
            transform.position = new Vector3(transform.position.x, position.y, position.z);
        }
    }

Movement Script

You can check out the scripts section on GitHub.

,

Leave a Reply

Your email address will not be published. Required fields are marked *