- Home /
How to check direction of wall on character controller hit?
Say you're in your game, running, and jump up in the air, and start sliding along a wall to your right. How would you tell which side of you the wall is on? So far I have this collision detected as shown below but stuck on this part. Been toying around with move direction and such. Is there a way to do it with components of controllercollider hit or should I send out 4 rays in each direction and see which hits first?(Would this be bad practice? Single/MP game?)
void OnControllerColliderHit(ControllerColliderHit hit) {
if (hit.collider.gameObject.tag == "Wall"){
print("Yay WALL!");
}
}
Edit: I was able to resolve this by checking hit normal then comparing angle of the transform right(right/left) and forward(front/back) to see which of the 4 directions was facing the wall(45 degrees). Thank you for your help!
Answer by robertbu · Feb 11, 2014 at 10:40 PM
There are a couple of approaches to this problem. A character controller has a set of collision flags. The flags tell you what part(s) of the character were impacted. You can directly access these flags by CharacterController.collisionFlags. These flags are also returned by the CharacterController.Move() function. They don't tell you which side, just that the sides were impacted.
Either independently or in combination with the collision flags, you can do some vector math using the hit point from the ControllerColliderHit parameter. To figure out which side, start by calculating the direction of the hit from the pivot point:
var dir = (hit.point - transform.position).normalized;
You can then get the angle between this vector and transform.forward, -transform.forward, transform.right and -transform.right. The side with the lowest angle is the one the hit is on. A slightly more efficient solution is to use Vector3.Dot() with these four directions.
Hm, I was under the impression the flags only said "sides" ins$$anonymous$$d of which side?
@$$anonymous$$ysta - you are absolutely right. I'd forgotten that it was only 'sides'. I rewrote my answer. Thanks.
Answer by Kavorka · Feb 11, 2014 at 11:24 PM
Check the normal vector. ControllerColliderHit.normal
Thanks! I'll compare that one against the above, my math is a bit rusty so I'm trying to think of ways to compare the way i'm facing to see which side is against the wall.
If vector3.Dot(transform.forward, ControllerColliderHit.normal) > 0 the character is looking away from wall otherwise the character is looking towards the wall. (Provided forward is forward)
I cannot upvote yet but I used a combo of both of your answers to work my solution, thank you all!