根据点偏移计算方向

som*_*guy 6 java math direction

对于基于平铺的游戏,我需要根据给定的点偏移(两点之间的差异)计算方向.例如,假设我站在点(10,4)并且我想要移动到点(8,6).我移动的方向是西北方向.计算这个的最佳方法是什么?

这是我在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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当然可以优化或缩短它.有帮助吗?谢谢.

Mat*_*nen 4

我认为最容易理解的方法是创建一个包含所有情况的值的静态数组。

// 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];
}
Run Code Online (Sandbox Code Playgroud)

编辑: 现在是正确的(为什么这么多语言缺少适当的sgn功能?)