ldavid
ldavid

Reputation: 2552

Collisions between CharacterController and BoxCollider

I'm trying to detect collision between the characterController and a platform (a rigidBody + boxCollider) in an Unity project.

I know that I can use this function at the characterController object:

void OnControllerColliderHit(ControllerColliderHit hit) {
    // [...];
}

But I would strongly rather to detect it in the platform object, in order to try to maintain the code clearer. Something like this:

void OnCollisionEnter(Collision c) {
    Debug.Log(c.gameObject.tag);
}

But it is not working! I searched in Unity forums and apparently the only way to detect a collision is to set the boxCollider's property isTrigger as True and using .OnTriggerEnter(Collider c) method instead. However, doing it will cause the player to fall through the platform, which obviously can't happen.

Alright, so my question is: is there another way to do it - whithout setting isTrigger as True - and detecting the collision in the platform object?

Thank you!

Upvotes: 1

Views: 8294

Answers (2)

Tomer Shahar
Tomer Shahar

Reputation: 343

I would like to suggest something very similar to what Steven Mills suggested, but may make things easier in the long run.

Add a child object to the player, that has a trigger collision box the size of the player (or just around it's feet if that's what you care about), but has a specific layer only for itself. In the project physics settings, make said layer only interact with the platform's layer. This means you won't trigger if this box hits anything else except for the platforms (like the rest of the player). Since the non triggers had not changed, the player and the platform will behave as you expect (just as with Steven's solution) but if you add new types of objects that you wish to land on/hit, and want them to work in a similar manner, you will not need double the prefabs/make 2 objects, just 1 with the correct layer assigned.

Upvotes: 0

Steven Mills
Steven Mills

Reputation: 2381

The way I handled a similar problem with a platform and a character controller, is by adding a child object to the platform with a trigger collider set to a larger size than the platform itself (think of it like an invisible box surrounding your platform). What this does is allow you to know if your player is going to hit the platform, the direction he's coming from etc. Then it's a simple matter of sending a message to the platform, with an necessary information parentPlatformObject.SendMessage(params)

Upvotes: 1

Related Questions