Shubhro
Shubhro

Reputation: 75

Cannot stay put on moving platform (OnTriggerEnter() not responding on certain occations)

I am building a 2.5D game in which there is a scenario where player jumps on top of the moving platform. It should remain still. For achieving this i have done the following:

In moving platform i have attached a RigidBody, two Box Colliders. One Box Collider for collision and second for trigger. The center of second Box Collider is little above the platform. Inspector of the platform

Scene view of platform

Below is the Moving_Platform.cs script attach to this platform.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Moving_Platform : MonoBehaviour
{
    // Start is called before the first frame update

    [SerializeField]
    private Transform _targetA, _targetB;

    [SerializeField]
    private float _speed = 1.0f;

    private bool _switching = false;
    void Start()
    {
        
    }

    // Update is called once per frame
    void FixedUpdate()
    {

        if(_switching){
            transform.position = Vector3.MoveTowards(transform.position, _targetA.position, _speed * Time.deltaTime);
        }else{
            transform.position = Vector3.MoveTowards(transform.position, _targetB.position, _speed * Time.deltaTime);
        }

        if(transform.position == _targetA.position){
            _switching = false;
        }else if(transform.position == _targetB.position){
            _switching = true;
        }
        
    }

    private void OnTriggerEnter(Collider other){
        if(other.tag == "Player"){
            other.transform.parent = this.transform;
            Debug.Log("Player");
        }
    }

    private void OnTriggerExit(Collider other){
        if(other.tag == "Player"){
            other.transform.parent = null;
        }
    }
}

when Player jumps on top of the platform it should stay put and become the child of the platform.(As per code under OnTriggerEnter()). But it only happens at the beginning of playing with some delay. After that when i jump or move a little on top of the platform, the Player doesn't stay put with the platform and OnTriggerEnter doesn't suppose to work.

Upvotes: 1

Views: 243

Answers (1)

Kitsomo
Kitsomo

Reputation: 133

Try moving this code:

  if(other.tag == "Player"){
                other.transform.parent = this.transform;
                Debug.Log("Player");
            }

into the OnTriggerStay(). Your player should have it as a parent for as long as they are in the trigger. After that, you should make sure you disable the parent some seconds after the jump has happened, in order to make sure that the player's x is still dependent on the platform, even if they are not on the trigger. This could be done with a coroutine.

Upvotes: 0

Related Questions