【问题标题】:Scratch-Based Movement in JavaJava中基于划痕的运动
【发布时间】:2017-12-03 21:18:45
【问题描述】:

我正在尝试编写一个程序,其中一个对象以一定的速度向一个方向移动。 Java 没有任何内置函数来确定方向。我将如何用 Java 编写下面的 Scratch Code?还有一种方法可以使一个对象指向另一个对象吗?
Screenshot of Scratch code to make object move in a direction or point toward mouse
我希望代码看起来像这样:

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

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

【问题讨论】:

  • 一个词:三角学。第一个问题请查看sincos,第二个问题请查看arctan
  • 我知道这与三角函数有关,但我的具体情况比这要复杂一些。我将问题编辑得更具体一些。

标签: java vector language-agnostic direction mit-scratch


【解决方案1】:

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

// 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;
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    • 2016-06-15
    • 2020-05-07
    • 2018-06-30
    相关资源
    最近更新 更多