- Home /
Trigger Enter Side on a cube
Hey guys, I would like to detect the side on which a trigger was entered/exited. I'm talking about a trigger in the shape of a cube. Is there any function that returns the side of a cube on which it was entered.
Thanks.
Answer by ScaniX · Aug 03, 2016 at 01:16 PM
When using a !IsTrigger collider, you could use the hit normal, but as you want to use a trigger, I can only suggest this imprecise approach in the OnCollision() method:
// Only works if not rotated or scaled: Vector3 delta = collider.gameObject.transform.position - gameObject.transform.position;
Vector3 delta = gameObject.transform.InverseTransformPoint(collider.gameObject.transform.position);
float xAbs = Mathf.Abs(delta.x);
float yAbs = Mathf.Abs(delty.y);
float zAbs = Mathf.Abs(delty.z);
if (xAbs > yAbs && xAbs > zAbs) {
// side is hit
if (delta.x < 0)
// left
else
// right
} else if (zAbs > yAbs) {
// front/back is hit
if (delta.z > 0)
// back
else
// front
} else {
// top/bottom is hit
if (delta.y > 0)
// top
else
// bottom
}
But if you need it a little more precise I would add 5 empty children with flat trigger collider boxes for the 5 additional (to the 1 already defined in the parent) sides. I think the latter would be my approach. :)
@ScaniX It works but only when the cube isn't deformed. When it's a thin cuboid it doesn't work anymore.
Any suggestions?
Btw: I need it to be one trigger.
I edited the answer to include rotation and scale of box, but I cannot test it at the moment. :)
Why do you need it to be one trigger? Child colliders would move and scale with the box just fine and they could still all call one method in the parent. It would just be more precise I think.
Your answer
![](https://koobas.hobune.stream/wayback/20220612090043im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Switching between areas in a scene with triggers 0 Answers
activate gui on trigger enter 1 Answer
OnTriggerEnter Get Key 1 Answer