Menu
CoddyTech

Move Toward a Point

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 35 of 85.

Vector3.MoveTowards(current, target, maxStep) returns a point up to maxStep closer to target. When the target is nearer than that, it returns the target itself, so it never overshoots. With speed * Time.deltaTime as the step, an object travels at a steady speed and stops exactly on the target. This cable car glides to its station at 2 units per second:

public Vector3 station = new Vector3(6, 3, 0);
public float speed = 2f;

void Update()
{
    transform.position = Vector3.MoveTowards(transform.position, station, speed * Time.deltaTime);
}

Once it arrives, every later call returns station again, so the car stays put, and transform.position == station is true. For a single number, Mathf.MoveTowards works the same way.

Vector3.Lerp(a, b, t) is the point a fraction t of the way from a to b: with t = 0.5 it is halfway. Written as Lerp(transform.position, station, 2f * Time.deltaTime) in Update(), it covers a share of the remaining distance on each frame: fast at first, slower and slower near the end, creeping closer instead of arriving at a set speed. Use MoveTowards when an object must travel at a set speed and stop exactly; use that Lerp pattern for a soft slow-down.

challenge icon

Challenge

Medium

Fly the drone to its landing pad when Space is pressed.

  1. Add fields bool flying; and bool landed;. On Input.GetKeyDown(KeyCode.Space), set flying = true;.
  2. While flying && !landed, move with Vector3.MoveTowards(transform.position, pad, speed * Time.deltaTime).
  3. When transform.position == pad, set landed and log Landed.

Press Play, then Space: the drone lands on the pad. Then Check.

Try it yourself

using UnityEngine;

public class Drone : MonoBehaviour
{
    public Vector3 pad = new Vector3(0, 0.25f, 0);
    public float speed = 2f;

    void Update()
    {
        // After Space: fly to pad at speed, and log Landed once on arrival
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground