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
MediumFly the drone to its landing pad when Space is pressed.
- Add fields
bool flying;andbool landed;. OnInput.GetKeyDown(KeyCode.Space), setflying = true;. - While
flying && !landed, move withVector3.MoveTowards(transform.position, pad, speed * Time.deltaTime). - When
transform.position == pad, setlandedand logLanded.
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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground