views:

975

answers:

2

Hi, I would like to get some code in AS2 to interpolate a quadratic bezier curve. the nodes are meant to be at constant distance away from each other. Basically it is to animate a ball at constant speed along a non-hyperbolic quadratic bezier curve defined by 3 pts. Thanks!

+3  A: 

The Bezier curve math is really quite simple, so I'll help you out with that and you can translate it into ActionScript.

A 2D quadratic Bezier curve is defined by three (x,y) coordinates. I will refer to these as P0 = (x0,y0), P1 = (x1,y1) and P2 = (x2,y2). Additionally a parameter value t, which ranges from 0 to 1, is used to indicate any position along the curve. All x, y and t variables are real-valued (floating point).

The equation for a quadratic Bezier curve is:

P(t) = P0*(1-t)^2 + P1*2*(1-t)*t + P2*t^2

So, using pseudocode, we can smoothly trace out the Bezier curve like so:

for i = 0 to step_count
    t = i / step_count
    u = 1 - t
    P = P0*u*u + P1*2*u*t + P2*t*t
    draw_ball_at_position( P )

This assumes that you have already defined the points P0, P1 and P2 as above. If you space the control points evenly then you should get nice even steps along the curve. Just define step_count to be the number of steps along the curve that you would like to see.

Naaff
+1  A: 

Please note that the expression can be done much more efficient mathematically.

P(t) = P0*(1-t)^2 + P1*2*(1-t)*t + P2*t^2

and

P = P0*u*u + P1*2*u*t + P2*t*t

both hold t multiplications which can be simplified.

For example:

C = A*t + B(1-t) = A*t + B - B*t = t*(A-B) + B = You saved one multiplication = Double performance.

While it might be true that you can save a few multiplies, the Bernstein basis is inherently more numerically stable. So if precision is a concern, the polynomial should *not* be reorganized. Admittedly, this won't matter much for animating a ball, but this is a huge deal in CAD packages.
Naaff