Moving Platform
How to create a moving platform in Unity
In this article we will create a moving platform for our platformer game.
As always there are various way to do the same thing in programming this is just one of the many.
We will be using Vector3.MoveTowards.
Moving Platform Script
We use game objects with just transform components as a reference. Our moving platform will be moving between these points. We assign these points from the Inspector.
Also we define a speed value with which we can adjust the speed our moving platform moves.
In Update() we move our platform towards our current target.
We also measure the distance from the current platform position to the target points A and B. If it reaches a certain point it will switch the target to the other point. This way the platform will ping pong between these points indefinitely.
[SerializeField] private Transform _pointA, _pointB;
private Transform _target;
private float _speed = 1f;
void Start()
{
_target = _pointA;
}void Update()
{
transform.position = Vector3.MoveTowards(transform.position,_target.position, _speed * Time.deltaTime); if (Vector3.Distance(transform.position, _pointA.position) < 0.001f)
{
_target = _pointB;
}
else if (Vector3.Distance(transform.position, _pointB.position) < 0.001f)
{
_target = _pointA;
}
}