0
votes

I have a 2D animation in Javascript, and I need a sprite to move from one point (x1, y1) to another point (x2, y2) on a set speed and direction. For example,

function update(speedX, speedY){
    x1 += speedX;
    y1 += speedY;
    if("(x1, y1) reach (x2, y2)"){
        // do other stuff
    }
}

In most cases, speedX and speedY are not equal, nor do they factor evenly into the distance needed to travel for each axis. I calculate the speedX and speedY values using a tangent function to compute the necessary velocity for a given speed and angle.

My question is, is there an algorithm that can do this? I would prefer something efficient since this has to be done 30 times a second, and it's float addition! Thanks!

3
your coords x1,y1,x2,y2 are related to the browser window?napolux
@Napolux No, they are just points inside a canvas object. Basically, the entire animation is it's own system (it's for a game), so I'm looking for a direct manual solution.Sefu
Ok thanks! I'll try to answer below :)napolux

3 Answers

0
votes

Usually (I developed some games in the past, nothing special btw) I used to see my sprites as rectangles and then I check for the overlapping of the two sprites using a very simple formula (look at this very good explanation).

Let's suppose you have to check collision between a point and a rectangle. You can apply the same formula, simplified, to check if the point stays between the rectangle area. In the case, read here.

0
votes

SOLUTION:

Okay, with some work I figured it out. First, I defined a function

function getSign(val) { ... }

that simply returns -1, 0, or 1 depending on whether the number passed in is negative, 0, or positive, respectively. Then, I did the following at the beginning (before any updates happened):

var xSign = getSign(x1-x2);
var ySign = getSign(y1-y2);

Finally, to check whether or not the point is currently at or just past the target (x2, y2), just check with this code:

function update(speedX, speedY){
    x1 += speedX;
    x2 += speedY;
    var curXsign = getSign(x1-x2);
    var curYsign = getSign(y1-y2);
    if( curXsign != xSign || curYsign != ySign ||
        (curXsign == 0 && curYsign == 0)){
            // do other stuff
    }
}

Basically, if either sign of the relative vector distance between X or Y changes sign, that means that axis went past the point. If both curXsign and curYsign are 0, that means it's right on the target point. Either of these three cases mean that you are on or just went past the target point. Tested and works.

Another possible solution would be to test the distance between the start point and the current location (curDist), and compare it to the distance between the start point and the target point (dist). Once curDist >= dist, you know you are at or past the target point.

0
votes

It is in the $1F port of the VIC-II:

PRINT PEEK(53279)

:-)