Move Towards in Unity is a function that allows you to change a value over time towards a target, controlled by a maximum rate of change (the max delta).
There are four types of Move Towards function in Unity, depending on the type of value that you want to change:
- Mathf.MoveTowards (modifies a float value)
- Vector2.MoveTowards (modifies a Vector 2 value)
- Vector3.MoveTowards (modifies a Vector 3 value)
- Vector4.MoveTowards (modifies a Vector 4 value)
Each of the different Move Towards functions modifies a different type of numerical value but all four work in the same way, and accept three parameters:
- The current value, which is the value that you’re changing
- The target value, which is the value that you’d like to reach
- The max delta, which is the maximum rate of change allowed in a single frame, typically a unit of speed that’s scaled by Delta Time.
The value that’s returned from the Move Towards function will be the new increased or decreased value or, if the value has reached its target, the target value, without going over.
public Vector3 targetPosition;
public float speed=10;
void Update()
{
transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
}
Move Towards is useful for controlling value change by speed, and is ideal for regenerating health bars, moving objects, or transitioning between two states smoothly.
The key benefit of Move Towards is that it allows you to control how fast a value changes. This means that, when using Move Towards, a health bar that’s refilling from half way will increase at the same rate as if it started from empty.
This is in contrast to Lerp, which is useful for changing values where time is the controlling factor (e.g. you want to control how long the movement takes, no matter how much it changes).
See also: