Moving 2D platforms

Hey guys, im trying to get the player ‘object’ to ‘stay’ into a moving platform.
For now, whenever i jump on it the player doesnt ‘stuck’ into.

Video reference attached.

Can anybody help?

Hi @farrico

This is not a Unity specific problem, so google for platformer game articles + moving platform articles, there are several. And there are several Unity specific tutorial videos.

And you shared very little info about your setup - actually, you didn’t share anything… so can’t help with the details.

But in general - what you’ll have to do, is to first detect are you on a moving platform, this is just a matter having some trigger or detecting grounded state over some specific object.

Then the movement part.

When your platform is moving it has certain velocity vector, which your player doesn’t have. You jump up or stand still, your character has no idea about platform so it will jump straight up or slide off from a platform. A solution is usually (depending on choices you made - of which I have no idea because you didn’t tell) to add the current velocity of the platform to your character’s velocity. So if your platform moves in this frame 1m right, you have to add that to your player’s velocity.

1 Like

For the player to stay on the platform with movement. You only need to make the player a son of the platform, when the player detected through OnCollisionEnter2D, Raycast, Overlap, etc that he touched the platform.

For make an object a child of another object is:

object.transform.SetParent(obect2.transform);

For undo this is:

object.transform.SetParent(null);

1 Like

this can be depended on the input. In some case you can just add more friction.

If the more friction will not help then you are perhaps move your player over the change in the rigidbodies velocity directly. Something like: rb.velocity = new Vector2 (Input.GetAxis (“Horizontal”) * speed, rb.velocity.y). Then the zero in the input stops the moving. You can try to disable zero-input on the platform and make player the child from the platform for this time.

ok, not the exactly script, just an example (maybe it is wrong somewhere):

void OnCollisionEnter2D (Collision col) {
if (col.CompareTag ("Player") {
col.gameObject.transform.parent = gameObject.transform;
col.gameObject.GetComponent<NameOfTheMovingScript>().isOnThePlatform = true;
}

void OnCollisionExit2D (Collision col) {
if (col.CompareTag ("Player") {
col.gameObject.transform.parent = null;
col.gameObject.GetComponent<NameOfTheMovingScript>().isOnThePlatform = false;
}

then in the players script:

public bool isOnThePlatform;

void FixedUpdate () {
if (!isOnThePlatform) {
//move normal
rb.velocity = new Vector2 (Input.GetAxis ("Horizontal") * speed, rb.velocity.y);
} else
if (Input.GetAxis ("Horizontal") !=0 && isOnThePlatform) {
//move on the platform by some input
rb.velocity = new Vector2 (Input.GetAxis ("Horizontal") * speed, rb.velocity.y)
}
1 Like