Moving Platforms in Unity
How can this be so hard? A post mortem of failing until you kinda make it.
I never thought moving platforms were all that special. That is until I tried to program one and discover all the ways they can be a pain. The above image is the product of two days of trial and error, lots of caffeine and a little bit of cursing, begging and maybe even a little praying. Luckily just before I got to the animal sacrifice stage the above happened.
So what all can go wrong? Well let’s look at all the ways this can go sideways. First a note about my setup. The sphere is my player, it is using a character controller component and the platforms all have box colliders. You can see from the screen cap that the player has no trouble standing on the flat platform. No code needed, so moving platform should be the same right? Well first I had to get the platform moving. That was going to require some code so I setup the following moving platform script.
[SerializeField] private List<Transform> waypoints;
[SerializeField] private float moveSpeed = 5f;
private int _currentWaypoint;
// Start is called before the first frame update
private void Start()
{
if (waypoints.Count <= 0) return;
_currentWaypoint = 0;
}
// Update is called once per frame
private void FixedUpdate()
{
HandleMovement();
}
private void HandleMovement()
{
transform.position =…