Reputation:
If you have a sprite at position (100, 100) and want to move it along a line to position (200, 300), how do you do so in increments of say 5 pixels max. At the moment, I am simply using the difference in x/y position to calculate the length and move the sprite 1/10 of the length at a time.
Instead I want it to move by 5 pixels max. So for this example, as the next y position is 2x as far away than the next x position, it should be moving 2x further in the y direction such that the sprite arrives at the position via a straight line.
Current code:
public void move() {
double currentX = this.getCenterX();
double currentY = this.getCenterY();
double nextX = next.getCenterX();
double nextY = next.getCenterY();
// Used to jump by 1/10 edge length
double xDif = Math.abs(currentX - nextX);
double yDif = Math.abs(currentY - nextY);
// Move by 1/10 the length in correct direction
if (currentX > nextX) {
this.setX(this.getX() - (xDif/10));
} else if (currentX < nextX) {
this.setX(this.getX() + (xDif/10));
}
if (currentY > nextY) {
this.setY(this.getY() - (yDif/10));
} else if (currentY < nextY) {
this.setY(this.getY() + (yDif/10));
}
}
Upvotes: 0
Views: 366
Reputation: 23664
To get the movement vector you first need to get the direction vector in order to get the direction's unit vector (a vector which is one in length).
The direction vector is the delta (difference) between your start and finish points x1 - x0, y1 -y0
.
To get the unit vector, you take each vector component (x, y)
and divide it by the vectors total magnitude sqrt(x^2 + y^2)
.
double xDirection = currentX - nextX;
double yDirection = currentY - nextY;
double magnitude = Math.sqrt(xDirection*xDirection + yDirection*yDirection);
double xUnit = xDirection/magnitude;
double yUnit = yDirection/magnitude;
Now if you want to move only 5 pixels total, then you can make your movement vector by multiplying each component of the unit vector by 5:
double xMovement = xUnit * 5;
double yMovement = yUnit * 5;
this.setX(this.getX() + xMovement);
this.setY(this.getY() + yMovement);
Upvotes: 1