Skip to content Skip to sidebar Skip to footer

Help Me Improve My Basic Point To Point Move Animation Algorithm

Greetings, With javascript, I am trying to make a very easy animation, an image moves from one X and Y coordination to another X Y coordination. I have 4 constant such as: var star

Solution 1:

Sounds like you need (a variation of) the Bresenham line drawing algorithm.

Solution 2:

The shortest distance between two points is a straight line. So you should probably move along that.

What that would imply is that in your code, you should not use the same step amount for both X and Y coordinates. Instead compute Y step based on X step and the slope of the shortest path line.

slope = (startY - endY) / (startX - endX);Y_step = X_step * slope;

Secondly, in your current algorithm, once your image reaches the destination point, it'll continue to oscillate about it. I think you should get rid of the statements that take a negative step.

Solution 3:

Since you are always moving two coordinates together, you only need to check against one of them, e.g.

if (currentX < endX) {
    currentX += xStep;
    currentY += yStep;
}

Solution 4:

Try something like this to move the object in a straight line:

var numberOfSteps = 100;
var stepDX = (endX - startX) / numberOfSteps;
var stepDY = (endY - startY) / numberOfSteps;
var step = 0;

Inside the move() function:

if (step <= numberOfSteps) {
    currentX = startX + stepDX * step;
    currentY = startY + stepDY * step;
    step++;
}

Cast currentX/currentY to integer before applying to the object you want to move.

Solution 5:

This is my implementation, many thanks to Frederik The Fool

Compute slope:

if(this.x === target.x){
    this.slope = 1;
}else{
    this.slope = (this.y - target.y)/(this.x - target.x);
}

Ystep:

if(this.y > this.target.y){ 
    this.y = Math.max(this.target.y, this.y - Math.abs(this.slope * distance));
}elseif(this.shape.y < this.target.y){
    this.y = Math.min(this.target.y, this.y + Math.abs(this.slope * distance));
}

Post a Comment for "Help Me Improve My Basic Point To Point Move Animation Algorithm"