Menu
CoddyTech

A Smooth Lane Change

Lesson 2 of 20 in Coddy's Unity Game: Sky Lanes course.

The runner jumps from lane to lane in a single frame. It works, but it looks like teleporting. A lane change should take a moment, so the eye can follow it.

Mathf.MoveTowards(current, target, maxStep) moves a number towards a target by at most maxStep, and never past it. Called every frame with a step of speed times Time.deltaTime, it moves at that speed in units a second, whatever the frame rate:

float x = Mathf.MoveTowards(transform.position.x, targetX, laneSpeed * Time.deltaTime);

With laneSpeed at 16 a lane change of 2.5 units takes about 0.16 seconds: quick, but you see it.

challenge icon

Challenge

Easy
  1. Add public float laneSpeed = 16f; under laneWidth.
  2. Replace float x = targetX; with the Mathf.MoveTowards line above.
  3. Press Play and change lanes.

Try it yourself

using UnityEngine;

public class Runner : MonoBehaviour
{
    public float laneWidth = 2.5f;

    public int lane;

    private CharacterController controller;

    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow)) lane = Mathf.Max(-1, lane - 1);
        if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow)) lane = Mathf.Min(1, lane + 1);

        float targetX = lane * laneWidth;
        float x = targetX;
        Vector3 move = new Vector3(x - transform.position.x, 0f, 0f);
        controller.Move(move);
    }
}

All lessons in Unity Game: Sky Lanes

Practice on your own: Unity playground