Getting the player to move with platform: Velocity, DistanceJoint, or...?

Hello, my player is parented to the platform OK if I move its position, but if I want a platform to move in a constant direction by applying velocity, the player just slides off. I’ve read what I could in other answers, but haven’t found exactly what I need. Here’s the code I’m trying to use:

using UnityEngine;
using System.Collections;
	
	public class MoveWithScript : MonoBehaviour {
		
	void  OnCollisionEnter2D (Collision2D other)
	{ 
	if (other.gameObject.tag == "Player") {
		other.transform.parent = gameObject.transform;
		other.gameObject.rigidbody2D.velocity = gameObject.rigidbody2D.velocity;
		}
		}
				
	void  OnCollisionExit2D (Collision2D other){ 
		if (other.gameObject.tag == "Player") {
		other.transform.parent = null;
		other.gameObject.rigidbody2D.velocity = other.gameObject.rigidbody2D.velocity;
		}
	}
}

Thanks for reading. Your help is greatly appreciated :slight_smile:

Do not parent a rigidbody to another rigidbody. You will get quirky results.

Rather try joint to make your player stick to the platform.

You could make your code work as is just by changing to OnCollisionStay. Ultimately this will lock your players movement to match the platforms movement, which is typically undesirable.

A better method would be to compare the velocity of the player and the platform, and add force to the player proportional to the difference in velocities.

You could get even more realistic performance by getting your players mass right (A human typically weighs between 60-80 kg). With the right physics material this should provide enough force from gravity to hold the player to your platform at low accelerations. No scripts required.