Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating direction based on point offsets

For my tile-based game, I need to calculate direction based on a given point offset (difference between two points). For example, let's say I'm standing at point (10, 4) and I want to move to point (8, 6). The direction I move at is north-west. What would be the best way to calculate this?

Here's me basic implementation in Java.

public int direction(int x, int y) {
    if (x > 0) {
        if (y > 0) {
            return 0; // NE
        } else if (y < 0) {
            return 1; // SE
        } else {
            return 2; // E
        }
    } else if (x < 0) {
        if (y > 0) {
            return 3; // NW
        } else if (y < 0) {
            return 4; // SW
        } else {
            return 5; // W
        }
    } else {
        if (y > 0) {
            return 6; // N
        } else if (y < 0) {
            return 7; // S
        } else {
            return -1;
        }
    }
}

Surely it can be optimised or shortened. Any help? Thanks.

like image 392
someguy Avatar asked Aug 29 '10 12:08

someguy


2 Answers

I think the easiest to understand way would be making a static array that contains the values for all cases.

// Won't say anything about how much these values make sense
static final int[][] directions = {
    {3,  6, 0},
    {5, -1, 2}, // -1 for "no direction", feel free to replace
    {4,  7, 1}
};

public int direction(int x, int y) {
    x = (x < 0) ? 0 : ((x > 0) ? 2 : 1);
    y = (y < 0) ? 0 : ((y > 0) ? 2 : 1);

    return directions[y][x];
}

Edit: Now it's correct (why are so many languages missing a proper sgn function?)

like image 160
Matti Virkkunen Avatar answered Sep 20 '22 05:09

Matti Virkkunen


My answers with if conditions :).

   public int direction(int x, int y) {
        //0 NE, 1 SE, 2 E, 3 NW, 4 SW, 5 W, 6 N, 7 S, 8 (Same place / Not a direction)  
        int direction = 0;

        if(x < 0){
            direction = 3;
        }else if(x == 0){
            direction = 6;
        }

        if(y < 0){
            direction = direction + 1;
        }else if(y == 0){
            direction = direction + 2;
        }
            return direction;
    }
like image 41
YoK Avatar answered Sep 24 '22 05:09

YoK