I am writing a 2D Platformer in Unity, and I am trying to get the player to stay on a moving platform. Now I searched and fumbled for a day or two, and I was out of luck.
Basically, they told me to try to move the character off the platform when they touch each other. Firstly, if I use anything related to OnTriggerEnter (), the player goes straight through the platform. If I do OnCollisionEnter () (using CharacterController on the player and BoxCollider on the platform), nothing happens at all. These are the two things I have found the most. The other is to educate the player on the platform, but this, apparently, causes "problems" (often stated, never explained).
So, how can I make a player stay on a moving platform? Here is the code for the moving platform:
public class MovingPlatform : MonoBehaviour
{
private float useSpeed;
public float directionSpeed = 9.0f;
float origY;
public float distance = 10.0f;
void Start ()
{
origY = transform.position.y;
useSpeed = -directionSpeed;
}
void Update ()
{
if(origY - transform.position.y > distance)
{
useSpeed = directionSpeed;
}
else if(origY - transform.position.y < -distance)
{
useSpeed = -directionSpeed;
}
transform.Translate(0,useSpeed*Time.deltaTime,0);
}
And here is the code for the player’s movement (in the update):
CharacterController controller = GetComponent<CharacterController>();
float rotation = Input.GetAxis("Horizontal");
if(controller.isGrounded)
{
moveDirection.Set(rotation, 0, 0);
moveDirection = transform.TransformDirection(moveDirection);
if(Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
{ running = true; }
else
{ running = false; }
moveDirection *= running ? runningSpeed : walkingSpeed;
if(Input.GetButtonDown("Jump"))
{
jump ();
}
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
EDIT: I think this may be due to how I define the player and platform, but I tried different combinations. If the platform is a trigger (at the collider), the player passes sequentially. If not, I cannot use the OnTrigger functions. I have a hard drive attached to both the player and the platform, but it does not seem to affect anything. When a player is on the platform in some settings, he trembles and often just ends in failure.