Hi, I’ve been recently trying to keep the controlled player, of which is controlled by a rigidbody, to stay on a moving platform in my 2D Platformer project. However, the player doesn’t move with the moving platform. Here’s my code:
using UnityEngine;
using System.Collections;
public class PlayerPlatformMove : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerStay2D(Collider2D other)
{
if (other.gameObject.tag == "MovingPlatform")
{
transform.parent = other.transform;
}
}
void OnTriggerExit2D(Collider2D other)
{
if (other.gameObject.tag == "MovingPlatform")
{
transform.parent = null;
}
}
}
Any help would be appreciated.
UPDATE:
It seems as if the parenting method does work, but for some reason the player moves at a slower speed as opposed to the platform, despite it now being a child of the platform. Here’s my code for the player:
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public float jump;
public float movespeed;
public float moveactual;
public bool grounded=true;
public bool finish=false;
public int score = 0;
public int orglev = 0;
public int jumpcount = 0;
public Transform prefab;
void Start () {
}
void Update () {
if (grounded) {
if (Input.GetKeyDown (KeyCode.Space)||Input.GetKeyDown(KeyCode.UpArrow)||Input.touchCount==1) {
GetComponent<Rigidbody2D> ().velocity = new Vector2 (GetComponent<Rigidbody2D> ().velocity.x, jump);
}
}
if (transform.position.y < -20) {
Application.LoadLevel ("Level1");
}
moveactual = 0;
if (Input.GetKey (KeyCode.D)||Input.GetKey(KeyCode.RightArrow)) {
moveactual=movespeed;
}
if (Input.GetKey (KeyCode.A)||Input.GetKey(KeyCode.LeftArrow)) {
moveactual=-movespeed;
}
GetComponent<Rigidbody2D> ().velocity = new Vector2 (moveactual, GetComponent<Rigidbody2D> ().velocity.y);
}
void OnTriggerEnter2D(Collider2D other){
if (other.tag == "Hills" || other.tag =="MovingPlatform") {
grounded = true;
}
if (other.tag == "Finish") {
finish = true;
orglev = orglev + 1;
}
if (other.tag == "Coin") {
Destroy (other.gameObject);
score++;
Debug.Log(score);
}
}
void OnTriggerExit2D(){
grounded = false;
}
void OnGUI(){
GUI.Label (new Rect (100, 200, 20, 20), score.ToString());
if (finish) {
if(GUI.Button (new Rect (Screen.width / 2 - 100, Screen.height / 2 + 10, 150, 20), "Next Level")){
Application.LoadLevel(orglev);
orglev = orglev + 1;
}
}
}
}
Why is that happening? Any help would again be appreciated.