Tutorials, extensions, and source files for ActionScript, Flash, and other Adobe products.

 

senocular.com ActionScript Library

BezierCurve.as

Name: Bezier Curve - simple two control point cubic bezier curve class
Author: senocular: www.senocular.com
Date: 1899-12-31T00:46:56.900
Documentation:
Bezier Curve with 2 control points.

Example:
 // Create end points and control points
endp1 = new Point(10,100);
controlp1 = new Point(10,10);
controlp2 = new Point(190,10);
endp2 = new Point(100,10);
 
// Create bezier curve
myCurve = new BezierCurve(endp1, controlp1, controlp2, endp2);
 
// set dots along bezier curve
for (i=0; i<50; i++){
	_root.attachMovie("dot", "d"+ ++depth, depth);
	myCurve.Position(_root["d"+depth], i/50);
}
 
// Put stars at control points
_root.attachMovie("star", "s"+ ++depth, depth);
myCurve.SetToPoint(_root["s"+depth], 2); // control point 2
_root.attachMovie("star", "s"+ ++depth, depth);
myCurve.SetToPoint(_root["s"+depth], 1); // control point 1
 
// A frame loop can be used to update the attached dots every frame
// The stars can be draggable movieclips and they can be used
// with SetPointTo to update the shape of the curve

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Basic point class - used in conjunction with bezier curve class
Point = function(x,y){
	this._x = x;
	this._y = y;
}
// Cubic BezierCurve class.  takes 4 points or movieclips or any objects with _x and _y
// properties and converts them to end points and control points to be used in curve
BezierCurve = function(endp1, controlp1, controlp2, endp2){
	this.x0 = endp1._x;
	this.y0 = endp1._y;
	this.x1 = controlp1._x;
	this.y1 = controlp1._y;
	this.x2 = controlp2._x;
	this.y2 = controlp2._y;
	this.x3 = endp2._x;
	this.y3 = endp2._y;
}
// positions a point or movieclip (pnt) along a BezierCurve based on position t
// t is a number from 0 to 1, where 0 is at endpoint1 and 1 is at endpoint2
BezierCurve.prototype.Position = function(pnt, t){
	var square = t*t;	var cube = t*t*t;
	var inv = 1 - t;	var invsquare = inv*inv;	var invcube = inv*inv*inv;
	pnt._x = invcube*this.x0 + 3*t*invsquare*this.x1 + 3*square*inv*this.x2 + cube*this.x3;
	pnt._y = invcube*this.y0 + 3*t*invsquare*this.y1 + 3*square*inv*this.y2 + cube*this.y3;
}
// changes the location of an endpoint or control point based on its number (as seen in class)
// to equal the position of point or movieclip passed (pnt)
BezierCurve.prototype.SetPointTo = function(num, pnt){
	this["x"+num] = pnt._x;
	this["y"+num] = pnt._y;
}
// Opposite of SetPointTo, changes the location of point (pnt)  to a end point or
// control point based on num
BezierCurve.prototype.SetToPoint = function(pnt, num){
	pnt._x = this["x"+num];
	pnt._y = this["y"+num];
}