-1

我正在尝试编写一个程序,其中一个对象以一定的速度向一个方向移动。Java 没有任何内置函数来确定方向。我将如何用 Java 编写下面的 Scratch Code?还有一种方法可以使一个对象指向另一个对象吗?
使对象朝一个方向移动或指向鼠标的 Scratch 代码的屏幕截图
我希望代码如下所示:

public void move(int direction, int distance) {
    // 0 degrees is up, 90 is right, 180 is down, 270 is left.
}

另外,如果您觉得有更好的方法来问这个问题,请给我提示,这是我在这个网站上的第一个问题。

4

1 回答 1

0

嗯,我是和一个非常擅长几何的朋友一起想出来的。这些是我们提出的功能:

// Movement
public void move(int speed) {
    x += speed * Math.cos(direction * Math.PI / 180);
    y += speed * Math.sin(direction * Math.PI / 180);
}
// Pointing toward an object
public void pointToward(SObject target) {
    direction = Math.atan2(target.y - y, target.x - x) * (180 / Math.PI);
}
// Pointing toward the mouse
public void pointTowardMouse() {
    direction = Math.atan2(Main.mouse.getY() - y, Main.mouse.getX() - x) * (180 / Math.PI);
}
// Ensure that the degrees of rotation stay between 0 and 359
public void turn(int degrees) {
    double newDir = direction;
    newDir += degrees;
    if (degrees > 0) {
        if (newDir > 359) {
            newDir -= 360;
        }
    } else if (degrees < 0) {
        if (newDir < 0) {
            newDir += 360;
        }
    }
    direction = newDir;
}

我想这可以帮助其他需要在游戏中进行旋转运动的人。

于 2017-12-04T14:06:30.433 回答