Move Toward a Point
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 27 of 67.
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
MediumThe drone waits in the air until you press Space. From then on it flies in a straight line to pad, the landing pad's position, at speed units per second, and lands exactly on it. When it lands, it logs Landed once, not again on every frame after.
Press Play, press Space, 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
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unity Scripting Basics
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon