I need to get the North, South, East or West Direction of a rigidbody’s movement. I can have North-East, or South-West. Only North, South, East or West.
Here is what I’ve tried so far, but to no avail :
int GetDirection()
{
int direction = previousDirection;
float angle = Vector3.Angle(Vector3.up, rigidbody.velocity);
angle = Vector3.Dot(Vector3.right, rigidbody.velocity.) > 0.0 ? angle : -angle;
Debug.Log(angle);
if(angle > 45 && angle <= 135)
{
direction = 1;
}
if ((angle > 135 && angle <= 180) || (angle < 0 && angle >= -45))
{
direction = 2;
}
if (angle < -45 && angle > -135)
{
direction = 3;
}
if ((angle < -135 && angle > -180) || (angle > 0 && angle < 45))
{
direction = 0;
}
direction = 0;
return direction;
}
0 being north
1 being east
2 being south
3 being west
The above assumes that Vector3.right and Vector3.forward are east and north. Any pair of perpendicular unit vectors will work.
If dotEast is positive, the direction is pointing “more east”.
If dorNorth is positive, the direction is pointing “more north”.
You could compare the absolute value of the two to see which is more important:
if (Mathf.Abs(dotEast) > Mathf.Abs(dotNorth)) {
//heading east/west
} else {
//heading north/south
//TODO: what if the values are equal?
//as written, this code assumes north/south
}
Angle from UP (what you’re starting with) isn’t helpful. It doesn’t give the angle around up – it tells you the angle to get to the up vector. Suppose the angle with UP is 90. That means the object is moving perfectly flat, but in any direction.
Using angle from forward would work better. Your dot-product test fixes the “can’t tell left from right” problem. But still a small problem. Suppose the object is moving mostly up, and a little north-ish. The angle will be 80 degree+, making you think you’re going south.
One fix is to use velocity without the y: Vector3 v = rigidbody.velocity; v.y=0; then use v, to get a “flat” angle from forward.
But, it seems easier to directly compare the values. If you’re going West, then the velocity will have -x as the largest. So:
Vector vv = rigidbody.velocity;
if(Mathf.Abs(vv.x)>Mathf.Abs(vv.z)) {
// x wins: North or south
if(vv.x>0) dir=N; else dir=S;
}
else {
// east or west:
if(vv.z>0) dir=E; else dir=W;
}
Here’s the solution I made right before leaving for work.
int GetCompassDirection()
{
int direction = previousDirection; //Debug.Log(rigidbody.velocity.normalized);
float normX = rigidbody.velocity.normalized.x;
float normY = rigidbody.velocity.normalized.y;
if(Mathf.Abs(rigidbody.velocity.x) > Mathf.Abs(rigidbody.velocity.y))
{
if(normX >= 0.1)
{
//East
direction = 1;
}
else if (normX <= -0.1)
{
//West
direction = 3;
}
}
else if (Mathf.Abs(rigidbody.velocity.x) < Mathf.Abs(rigidbody.velocity.y))
{
if(normY >= 0.1)
{
//North
direction = 0;
}
if (normY <= -0.1)
{
//South
direction = 2;
}
}
previousDirection = direction;
return direction;
}