How to tell if a collider is on the right or left of another collider?
I am creating a 2d game and I have four colliders in my scene. I need to be able to tell if one collider is right or left of one of the other colliders, using a c# script.
thanks for help in advance.
Answer by $$anonymous$$ · Sep 25, 2015 at 05:55 PM
When the collision happens, compare their x coordinates. If your player's x coordinate is bigger than your target's x coordinate, then your player is right to your target. If your player's x coordinate is smaller than your target's x coordinate, then your player is left to your target.
void checkCollidingSide(){
if (transform.position.x > target.transform.position.x) {
Debug.Log("Player is colliding on target's right side");
} else {
Debug.Log("Player is colliding on target's left side");
}
}
This works amazingly, the only change I made was I put the code in the update function, because I needed it to check every frame, not only when it collided. other than that this worked beautifully.
Answer by jrhowa · Sep 24, 2015 at 03:55 PM
You can check the location of each.. if position.x is less then your current collider position.x your checking then its to the left else its right.
Or if you need to know this information when you have a coalition you can check the same data inside the OnCollisionEnter, check the collided objects positions x value. If its lower then yours then its left.. else right.
Is that what your needing?
Your answer
![](https://koobas.hobune.stream/wayback/20220612034913im_/https://answers.unity.com/themes/thub/images/avi.jpg)