Archives:

Categories:

Topics:


Parabole movement in actionscript3

In my work a need arose for me to write formula which would allow me to send objects on a parabolic trajectory so that they, starting from some point, would go through two other points. The be more precise, I want an enemy to fly from his initial position towards player while passing through some point (so I can more or less control his flight’s trajectory). Here I assume that my enemy movement algorithm looks like this:

1
2
3
x += horizontalSpeed;
y += verticalSpeed;
verticalSpeed += gravity;

So, what looks like parabola? A diagram of quadratic equation of course! Quadratic equation is expressed by the formula:

1
y = a*x^2 + b*x +c;

We have three unknowns and three points, so we can calculate a formula for each unknown:

1
2
3
a = (x3*(y1-y2) + (x2-x1)*(y3-y1) + x1*(y2-y1)) / ((x2-x1)*(x3*x3 - x1*x1) + x2*x2*(x1-x3) + x1*x1*(x3-x1));
b = (y2 - a*x2*x2 - y1 + a*x1*x1) / (x2 - x1);
c = y1 - a*x1*x1 - b*x1;

Where (x1,y1), (x2,y2), (x3,y3) are the positions of the three points. Pretty simple so far, though it can be easy to make a mistake when finding these formulas by hand (took me three tries). We won’t actually be using c so you can omit it if you want.

Now we can calculate both the horizontal and vertical starting speed of our enemy. First we have to find the former to know how many pixels per step do we have to move horizontally so that the vertical speed is increased by ‘gravity’ value. It can be acquired from formula:

1
f(x) - f(x+dx) - f(x+dx) + f(x+2dx)

Which, after numerous transformations, gives us resulting horizontal speed:

1
horizontalSpeed = Math.sqrt(gravity / (2*a));

Now, aquiring the vertical speed can be a bit more tricky, as for this we need to know the tangent of the initial angle. You can do this either by calculating the angle somehow, eg. use something like this:

1
angle = Math.atan2(calc(x+0.001) - calc(x), 0.001)

Where calc() is a function which return the value of quadratic equation. Or, we can use the fact that the derivative of a quadratic equation is its directional compound, and directional compound is nothing else than the tangent of the angle we are looking for. So anyway, the vertical speed is the tangent of the initial angle multiplied by the horizontal speed, which gives:

1
2
verticalSpeed = Math.tan(angle) * horizontalSpeed;
verticalSpeed = (2*a*startingX + b) * horizontalSpeed;

I personally prefer the second method. The results are as follows:

Now, stay tuned for more!


You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.


No comments yet!


Leave a comment