My Player wont stick to the platform and I can't seem to fin a solution

So I am trying to make the player a child to the moving platform which is being moved by looking for waypoints and going to them. But when I make the player collide with the platform the collision enter is not detecting the player thus not making the player stay on it, it instead glides off.enter image description here

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

public class movePlatform : MonoBehaviour
{
    public GameObject[] waypoints;
    float rotSpeed;
    int current = 0;
    public float speed;
    float WPradius = 1;
    private GameObject target = null;
    private Vector3 offset;
    public GameObject Player;
CharacterController controller;

void Start()
{
    controller = GetComponent<CharacterController>();
}


void OnTriggerEnter(Collider other)
{
    if (other.gameObject.tag == "Player")
    {
        //This will make the player a child of the Obstacle
        controller.transform.parent = other.gameObject.transform;
    }
}

void OnTriggerExit(Collider other)
{
    controller.transform.parent = null;
}

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

    if (Vector3.Distance(waypoints[current].transform.position, transform.position) < WPradius)
    {

    current++;
        if (current >= waypoints.Length)
        {
            current = 0;
        }
    }

    transform.position = Vector3.MoveTowards(transform.position, waypoints[current].transform.position, Time.deltaTime * speed);

}

}

Upvotes: 0

Views: 53

Answers (1)

Maarti
Maarti

Reputation: 3719

This will not make the player a child of the platform:

controller.transform.parent = other.gameObject.transform;

Because here controller is the CharacterController instance, and other refers to the player collider. So they both refers to the player transform in the end.

Replace it by something like

other.transform.parent = transform;

or

controller.transform.parent = transform;

(Here, transform refers to the platform transform.)


If the OnTriggerEnter() is not detecting, check if your collider has isTrigger enabled. Or change the method to OnCollisionEnter().

If you are making a 2D game, switch these methods to the 2D version (=> OnCollisionEnter2D or OnTriggerEnter2D).

Upvotes: 1

Related Questions