MCMastery
MCMastery

Reputation: 3249

Get next point toward other point

I can't understand the http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm enough to write it in Java (I'm in 8th grade). From a starting point, I need to get a point toward a destination point. I have found several forum posts but no examples in Java.

I tried this (inside my Vector2 class):

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

But it never returns a negative x or y coordinate, and it just doesn't seem to be altogether accurate.

Upvotes: 0

Views: 105

Answers (1)

Marco13
Marco13

Reputation: 54709

In order to move towards a certain destination point by a certain amount, you have to compute the direction from the current point towards the target point, and multiply this direction with the speed that you want to use, before adding it to the original point:

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

Upvotes: 1

Related Questions