x


How to get collisions on Character controller?

I have the player with a character controller on him and an object with a box collider and a rigid body on it. What function do I need to use to get the collision between the two? I have tried OnCollisionEnter and OnControllerColliderHit in both objects and I'm getting nothing.

more ▼

asked Dec 26 '11 at 10:22 PM

gregthegeek gravatar image

gregthegeek
16 4 4 5

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

Use OnControllerCollider in the player script - but be aware that it will report collisions with the ground all the time (except when the player is jumping, of course). To filter out these collisions, you can check the hit.normal angle from the ground - if it's below a low angle (say, 45 degrees) the character collided with other thing than the ground:

function OnControllerColliderHit(hit: ControllerColliderHit){
  if (hit.normal.y < 0.707){
    // character collided with another thing (not the ground)
  }
}

This works because normal.y is numerically equal to the sin of the angle from the ground (it's a normalized vector).

Another alternative is to check if the object hit has a rigidbody, ignoring those that don't have it:

function OnControllerColliderHit(hit: ControllerColliderHit){
  if (hit.rigidbody){
    // character collided with a rigidbody
  }
}
more ▼

answered Dec 26 '11 at 11:40 PM

aldonaletto gravatar image

aldonaletto
42.5k 16 43 202

Whoops - I had put the script in a child of the player, I moved it to the parent and fixed it. You did clarify on which function to use, so thanks!

Dec 26 '11 at 11:52 PM gregthegeek
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x2584
x1948
x1864
x1765

asked: Dec 26 '11 at 10:22 PM

Seen: 2878 times

Last Updated: Dec 26 '11 at 11:52 PM