- Home /
How to detect on which side my character controller was hit?
I've just barely started messing with collision flags but they only detect a side hit and don't specify which side. I'm experimenting with 2D so I could have if my character is facing this direction and is hit on this side to get my desired result. Collision flags sometimes returns an integer not sure if I can use that to my advantage. Thank you in advance for any response.
Answer by robertbu · Jul 30, 2013 at 12:15 AM
One easy way is to compare the angle between the character controller and the center of the collier object.
function OnControllerColliderHit (hit : ControllerColliderHit) {
var v3 = hit.transform.position - transform.position;
var angle = Vector3.Angle(v3, transform.forward);
if (angle > 45.0 && angle < 135.0)
Debug.Log("Side hit");
}
This is not a perfect solution. The calculation is done from the middle of the character controller to the pivot. But unless the collider is on a capsule or a sphere, the hit is likely not at this exact position. You don't get contact points with a ControllerColliderHit. If this turns out to be a problem, you might try using Collider.ClosestPointOnBounds() as the point to use in generating the vector for the angle calculation. The second issue is that the angle is in 3D space. That is, if the object collided with is much shorter or taller, it can skew the angle upwards. That can be fixed by bringing the point used in the calculation to the 'y' level of the character controller. The calculation could be:
var v3 = hit.transform.position;
v3.y = transform.position.y;
v3 -= transform.position;
var angle = Vector3.Angle(v3, transform.forward);
hey robert what about something like
function OnTriggerenter(other : Collider)
{
if(other.tag=="Enemy" && other.position.x > position.x)
{
do this;
}
}
You know a lot more than I do. Do you think that might work or if not then something like it?
@superluigi - No I don't think it will work as is. For example say your character was hit just barely right of center in the front. Your code would call that a side hit. If you are using two capsule colliders, you might get something like this to work:
if (other.tag == "Enemy") {
var delta = $$anonymous$$athf.Abs(other.position.x - position.x);
if (delta > someValue) {
Debug.Log("Side hit");
}
}
Where 'someValue' would likely be around 1/2 of the character width.
IF your question is answered, please click on the checkmark next to the answer. Thanks.
Your answer
