I first discovered this algorithm when I tried to learn some more advanced collision techniques. Therefore, I decided to recreate the algorithm on my own. On Wikipedia I found the following algorithm for drawing curves with multiple anchor points:
This can be very hard and complicated to convert into a fully functional Flash application but I will try to guide you through some of the basic elements when converting algorithms like this into ActionScript.
The first step is to look through the algorithm and try to find out what we need. At the end of the line you can see that t has to be an element of an interval from zero to one. Therefore, we have to create a loop. It's important to notice that the loop can't increase with more than one since the loop then won't create more than two values.
To create a smooth curve you will have to choose a very small value that t increases with everytime the loop execute.
Here's one way to do it:
Code Snippet
- for (var t:Number=0; t<1; t+=0.001) {
Everytime the loop executes we want to get two values, x- and y-coordinates and then draw a line between the previous point and the new one. We now assume that we have two control points and one anchor point and we want to create a nicely curved line between the two control points.
As you can see in the algorithm the first part including a point (P) and the last part is different from the rest. Therefore we cannot make one single calculation function, we need 3.
We create a function were four variables have to be passed in. The current value of t, the total number of points (n), the current point(i) and the x or y value of that point(P).
Code Snippet
- private function calculate (t:Number,n:uint,i:uint,p:Number):Number {
- var sum:Number;
-
- if (i==0) {
- sum = Math.pow((1-t),n) * p;
- }
- if (i>0&&i<n) {
- sum = getBinomialCoefficient(n,i) * Math.pow(t,i) * Math.pow((1-t),n-i) * p;
- }
- if (i==n) {
- sum = Math.pow(t,n)*p;
- }
-
- return sum;
- }
The getBinomialCoefficient function simply takes the values of t and n and returns the binomial coefficient that we need in the algorithm.
By Lewinzki
Lewinzki.com and all of its content is created by Thomas Jensen alias Lewinzki. Email: webmaster@lewinzki.com
00:00:00