TopchetoEU
TopchetoEU

Reputation: 694

Unity get the trigger that has caused a OnCollision... event

I'm trying to make a player controller that jumps only when a specified in a property Collider collides with anything. For now, I can detect when a collision has occurred, but can't detect which are the two bodies that have collided. Does the event trigger only when one of the colliding bodies is the one that the script is applied to. If so, how can I handle events on behalf of other objects (or even better, detect global collisions)

Here is my player controller hierarchy:

Capsule
|
+- Camera
|
+- Floor Collider

P. s.: Sorry for the question's short length

Upvotes: 0

Views: 618

Answers (1)

tiggaxxxx
tiggaxxxx

Reputation: 49

Let me see if i got your question, you want to detect when the player is touching the floor so that it can only jump when on the floor. Is this right?

The floor has a Collider as well right? Add a tag on the floor object so that we can identify who is the Collider.

And then on the Player Controller do something like:

void OnCollisionEnter(Collision other)
{
    if(other.gameObject.tag == "floor") 
    {
        allowJump = true;
    }
}

And the opposite so that we know that the player can't jump

void OnCollisionExit(Collision other)
{
    if(other.gameObject.tag == "floor") 
    {
        allowJump = false;
    }
}

Upvotes: 1

Related Questions