Player slides off Moving Platform

How to move Player along with the Moving Platform

Tristan Engel
3 min readJan 9, 2022

In this article we will make our player move along with the moving platform instead of slide off.

Pseudocode / logic

To do make our player move along with the platform we will make the player a child object of the moving platform while it’s on it.

To check if the player is on the platform we will create another trigger.
On our Moving Platform add another Box Collider component.

Two Box Collider Components

On the 2nd Box Collider > Edit Collider > Adjust it so when our player is on the platform it will hit

Check is Trigger

Moving Platform Script

We can use the following reference to set the parent of the player to the moving platform.

To make this work we also need to use FixedUpdate() instead of Update(). Update() is called every frame and depend on how powerful the machine running the game is. FixedUpdate() is framerate independent and useful for physic based calculations.

The relevant parts are in bold. We changed Update() to FixedUpdate().
We both check for the player entering the moving platform collider to set the parent and the reverse when exiting the collider.

[SerializeField] private Transform _pointA, _pointB;
private Transform _target;
private float _speed = 2f;

void Start()
{
_target = _pointA;
}

void FixedUpdate()

{
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;
}
}

private void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
other.transform.SetParent(this.transform);
}
}

private void OnTriggerExit(Collider other)
{
if (other.tag == "Player")
{
other.transform.SetParent(null);
}
}

Clean Hierarchy — Prefab

When we want more moving platforms in our level we could just duplicate them, but that would get confusing really quick with many point A’s and B’s. A tip to make this clean and simple is to create a empty game object, set the transform to zero. Next drag in the moving platform and both points in to the empty game object. Finally prefab the game object by dragging it into the Project panel.

Moving platform Prefab

--

--

Tristan Engel

Aspiring developer that’s self-learning Unity & C# to transition to a career with Unity. I got a passion for creating interactive experiences.