获得下一点指向其他点

时间:2014-12-07 22:45:56

标签: java math vector

我无法理解http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm足以用Java编写它(我在8年级)。从一个起点开始,我需要指向目的地点。我找到了几个论坛帖子,但没有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坐标,它似乎并不完全准确。

1 个答案:

答案 0 :(得分:1)

为了向特定目标点移动一定量,您必须计算从当前点到目标点的方向,然后乘以方向在将其添加到原始点之前,使用您要使用的speed

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