gpt4 book ai didi

java - 获取指向其他点的下一个点

转载 作者:行者123 更新时间:2023-12-01 12:09:21 24 4
gpt4 key购买 nike

我无法理解 http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm足以用 Java 编写它(我在八年级)。从起点开始,我需要到达目的地。我发现了几个论坛帖子,但没有 Java 示例。

我尝试了这个(在我的 Vector2 类中):

public Vector2 getNextPointTowardOther(Vector2 dest, int speed) {
if (dest == null)
return this;
double deltaX = dest.getX() - this.x;
double deltaY = dest.getY() - this.y;
double direction = Math.atan(deltaY / deltaX);
double x = this.x + (speed * Math.cos(direction));
double y = this.y + (speed * Math.sin(direction));
return new Vector2(x, y);
}

但它永远不会返回负的 x 或 y 坐标,而且它似乎并不完全准确。

最佳答案

为了向某个目标点移动一定的量,您必须计算从当前点到目标点的方向,并将该方向相乘与您想要使用的速度,然后将其添加到原始点:

public Vector2 getNextPointTowardOther(Vector2 dest, int speed) {
if (dest == null)
return this;
double deltaX = dest.getX() - this.x;
double deltaY = dest.getY() - this.y;

// Compute the distance
double distance = Math.sqrt(deltaX*deltaX+deltaY*deltaY);

// Compute the (normalized) direction
double dirX = deltaX / distance;
double dirY = deltaY / distance;

// (The vector (dirX, dirY) now has length 1.0)

double x = this.x + speed * dirX;
double y = this.y + speed * dirY;
return new Vector2(x, y);
}

关于java - 获取指向其他点的下一个点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27348785/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com