Search Unity

How can I get the player to stay on the moving platform?

Discussion in 'Scripting' started by CoolKrit, Jan 12, 2019.

  1. CoolKrit

    CoolKrit

    Joined:
    Aug 21, 2018
    Posts:
    5
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class MovingPlatform : MonoBehaviour
    5. {
    6.     public Vector3 finishPos = Vector3.zero;
    7.     public float speed = 0.5f;
    8.  
    9.     private Vector3 _startPos;
    10.     private float _trackPercent = 0;
    11.     private int _direction = 1;
    12.  
    13.     // Use this for initialization
    14.     void Start()
    15.     {
    16.         _startPos = transform.position;
    17.     }
    18.  
    19.     void OnDrawGizmos()
    20.     {
    21.         Gizmos.color = Color.red;
    22.         Gizmos.DrawLine(transform.position, finishPos);
    23.     }
    24.  
    25.     // Update is called once per frame
    26.     void Update()
    27.     {
    28.         _trackPercent += _direction * speed * Time.deltaTime;
    29.         float x = (finishPos.x - _startPos.x) * _trackPercent + _startPos.x;
    30.         float y = (finishPos.y - _startPos.y) * _trackPercent + _startPos.y;
    31.         transform.position = new Vector3(x, y, _startPos.z);
    32.  
    33.         if ((_direction == 1 && _trackPercent > .9f) || (_direction == -1 && _trackPercent < .1f))
    34.         {
    35.             _direction *= -1;
    36.         }
    37.     }
    38. }
     
    Last edited: Jan 12, 2019
  2. Lethn

    Lethn

    Joined:
    May 18, 2015
    Posts:
    1,004
    A very common way of doing this is to parent your player to the platform itself when the player enters the collider and then unparent the player when you exit the collider. Do you want me to give you a link to a tutorial that goes into a full explanation of it all?
     
    CoolKrit likes this.
  3. CoolKrit

    CoolKrit

    Joined:
    Aug 21, 2018
    Posts:
    5
  4. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    1,232
    RustyCrow likes this.
  5. Lethn

    Lethn

    Joined:
    May 18, 2015
    Posts:
    1,004