0
\$\begingroup\$

Objective

  • To convert body.getAngle() to 4 direction (NSEW), when torque or angularvelocity is used

Because box2d body default angle is zero, I used it as reference to create my character direction. 0 degree means West, 90 degree North, 180 degree East and 270 is south, with a range of 45 degree. When I manually transform the body I get the right direction, but when I use the body.setAngularVelocity() or body.applyTorque() I get a different angle, which is more than 360 degree, assume body.angle() * RADIAN_TO_DEGREE. I am only expecting 0 to 360 degree without negative.

public static SteerDirection getDirection(float degreeAngle) {
    SteerDirection direction = SteerDirection.NONE;
    if(degreeAngle > 0 && degreeAngle < 22.5 || degreeAngle > 337.5 && degreeAngle < 360){
        direction = SteerDirection.WEST;
    }

    if(degreeAngle > 22.5 && degreeAngle <67.5) {
        direction = SteerDirection.NORTH_WEST;
    }

    if(degreeAngle > 67.5 && degreeAngle < 112.5){
        direction = SteerDirection.NORTH;
    }

    if(degreeAngle > 112.5 && degreeAngle < 157.5){
        direction = SteerDirection.NORTH_EAST;
    }

    if(degreeAngle > 157.5 && degreeAngle < 202.5){
        direction = SteerDirection.EAST;
    }

    if(degreeAngle > 202.5 && degreeAngle < 247.5){
        direction = SteerDirection.SOUTH_EAST;
    }

    if(degreeAngle > 247.5 && degreeAngle < 292.5) {
        direction = SteerDirection.SOUTH;
    }

    if(degreeAngle > 292.5 && degreeAngle < 336.5) {
        direction = SteerDirection.SOUTH_WEST;
    }

    return direction;
}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

You can convert angles that are beyond 0 and after 360 back to 0~360 by doing:

float angle = -180f;
angle %= 360f;
if(angle < 0) angle += 360;

That aside, I'm not really sure your cardinal directions are right. I'd assume you're better of forgetting about angles and converting them to vectors. Then you'll have a solid basis to work on. Take a look:

float angleInDegrees = 180f;
Vector2 direction = new Vector2(1, 0); //Put here your default direction with length 1. This usually is a vector. pointing right.
direction.rotate(angleInDegrees);
if(Math.abs(direction.x) > 0.707) { //a perfect diagonal in unit circle
    direction.x = Math.signum(direction.x);
} else {
    direction.x = 0;
}
if(Math.abs(direction.y) > 0.707) {
    direction.y = Math.signum(direction.y);
} else {
    direction.y = 0;
}

Now you have a vector pointing exactly to (0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (1, -1), (-1, 1) or (-1, -1). The 8 cardinal points you described. You can easily convert this vector to your cardinal points if you wish.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .