BasicHermite
Very basic demo of computing a point along a Hermite curve. Doubleclick to reset (this also randomizez the last cotrol point a bit)
/**
* Copyright George.Profenza ( http://wonderfl.net/user/George.Profenza )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/pTgv
*/
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Point;
/**
* @author george
*/
public class BasicHermite extends Sprite {
private var percent:Number = 0;
private var P0:Point = new Point(10,90);//1st control pt
private var T0:Point = new Point(300,200);//1st anchor pt - NOTE! The anchors are relative to the controls
private var P1:Point = new Point(400,90);//2nd control pt
private var T1:Point = new Point(-100,400);//2nd control pt
private var points:Array = [P0,T0,P1,T1];
private var pointAtPercent:Point;
public function BasicHermite() {
init();
}
private function init():void{
stage.doubleClickEnabled = true;
stage.addEventListener(MouseEvent.DOUBLE_CLICK, reset);
reset();
}
private function reset(event : MouseEvent = null) : void {
P1.x = 200 + Math.random() * 200;//randomize a wee bit
T1.x = Math.random() * 200 - 100;
graphics.clear();
percent = 0;
this.addEventListener(Event.ENTER_FRAME, draw);
}
private function draw(event : Event) : void {
pointAtPercent = hermite(percent, points);//compute point
if(percent == 0) graphics.moveTo(pointAtPercent.x,pointAtPercent.y);//draw
graphics.lineStyle(5,0x009900,percent);
graphics.lineTo(pointAtPercent.x,pointAtPercent.y);
percent += .015;//update percentage of traversal along curve
if(percent >= 1) removeEventListener(Event.ENTER_FRAME, draw);//done
}
/*
* Computes x,y values for a given traversal of a Hermite Curve
* @param t:Number - a normalized value (0.0 to 1.0) describing path traversal
* @param points:Array - an array contining the 4 points describing the curve (P0,T0,P1,T1 - always in this order)
* Anchor points are relative to they're control points
*/
private function hermite(t:Number,points:Array):Point{
var result:Point = new Point();
result.x = (2 * Math.pow(t,3) - 3 * t * t + 1) * points[0].x+
(Math.pow(t,3) - 2 * t * t + t) * points[1].x +
(- 2 * Math.pow(t,3) + 3*t*t) * points[2].x +
( Math.pow(t,3) - t*t) * points[3].x;
result.y = (2 * Math.pow(t,3) - 3 * t * t + 1) * points[0].y+
(Math.pow(t,3) - 2 * t * t + t) * points[1].y +
(- 2 * Math.pow(t,3) + 3*t*t) * points[2].y +
( Math.pow(t,3) - t*t) * points[3].y;
return result;
}
}
}