ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Example: Animating Composite Objects Using Inverse Kinematics | 231

You may be wondering why theupdate( )method was not implemented in the


Componentclass. We implemented the most basic form of inverse kinematics in this


case. Our snake is a real contortionist and is able to freely rotate around its joints.


The real power of inverse kinematics is realized when limiting angles are introduced.


Limiting angles bring constraints to joint rotation, just like the elbow joint restricts


the angle of motion of the forearm. Introducing different limiting angles will make


theupdate( ) method implementations unique for different segments. Therefore,


Example 6-16. Tail.as


package
{
import flash.geom.Point;


public class Tail extends Component
{


private var segLen:Number = 20;


public function Tail(color:uint = 0xC0C0C0)
{
graphics.lineStyle(10, color);
graphics.moveTo(0, 0);
graphics.lineTo(segLen, 0);
graphics.lineStyle(3, 0x000000);
for (var i:uint = 1; i < 4; i++)
{
graphics.moveTo(i 5, -5);
graphics.lineTo(i
5, 5);
}
}


override public function update( ):void
{
var myParent:Composite = this.getParent( );
var parentLoc:Point = new Point(myParent.x, myParent.y);
var myLoc:Point = new Point(this.x, this.y);


// rotate to orient to parents new location
var tempPoint:Point = parentLoc.subtract(myLoc);
var angle:Number = Math.atan2(tempPoint.y, tempPoint.x);
this.rotation = angle * 180 / Math.PI;


// move to maintain distance
var currentDistance:Number = Point.distance(
parentLoc, myLoc);
var myNewLoc:Point = Point.interpolate(myLoc, parentLoc,
segLen / currentDistance);
this.x = myNewLoc.x;
this.y = myNewLoc.y;
}
}
}

Free download pdf