- Home /
How detect player is which side of box?
I have a 3d box like this picture. An a player in 3d. Now how can I detect which side of box my player is? 1 or 2.
Answer by Baste · May 22, 2015 at 04:28 PM
You just check the player's coordinates and the box's coordinates:
if(box.transform.position.z > player.transform.position) {
// player is on side 1
}
else {
// player is on side 2
}
If this is supposed to work not matter what the box's rotation is, you'll have to transform the player's position to the box's local space, and check if the player is below the box' position. In the box's local space, the box's position is (0, 0, 0), so in that case, you just check if the player has a negative z:
if(box.transform.InverseTransformPoint(player.transform.position).z < 0) {
// player is on side 1
}
else {
// player is on side 2
}
If you only want to know this while the player is touching the box, put it in your OnTrigger/CollisionEnter.
Answer by AMIR_REZAs · May 23, 2015 at 02:49 PM
Here is answer worked from Iron-Warrior
What you're really asking is to test which side of a plane (your box wall) a point (game object position) is on. A plane is defined by a normal (the direction it's pointing) and a location. To check which side of it a point is one, you take the direction from the origin of the plane to the point. If the angle between the direction and your plane's normal is greater than 90 degrees, is on the backside of the plane.
Taking the origin of your plane to be the center of your box...
Vector3 direction = playerPosition - planeOrigin;
if (Vector3.Angle(direction, planeNormal) > 90)
{
// do something
}
This is a good way of testing this since it works in all directions and all dimensions.
Your answer
Follow this Question
Related Questions
Adding quaternions using a seperate axis 0 Answers
How to make Y-Axis face away from a position? 2 Answers
Write a C# script to record GameObject rotation? 4 Answers
Drag to Rotate using Arcball theory ( 3 axis ) 0 Answers
How to rotate on one axis while keeping the other axes open to be rotated by other scripts? 1 Answer