Search Unity

  1. Unity 2018.3 is now released.
    Dismiss Notice
  2. The Unity Pro & Visual Studio Professional Bundle gives you the tools you need to develop faster & collaborate more efficiently. Learn more.
    Dismiss Notice
  3. We've updated our Terms of Service. Please read our blog post from Unity CTO and Co-Founder Joachim Ante here
    Dismiss Notice
  4. Want to provide direct feedback to the Unity team? Join the Unity Advisory Panel.
    Dismiss Notice
  5. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    Dismiss Notice

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:
    4
    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:
    882
    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:
    4
  4. eses

    eses

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

    Lethn

    Joined:
    May 18, 2015
    Posts:
    882