Search code examples
javamathdirection

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.


Solution

  • 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?)