Example: Animating Composite Objects Using Inverse Kinematics | 225
Both theComponentandCompositeclasses should behave as abstract classes; they
need to be subclassed. We will develop theHeadandBodySegmentclasses that sub-
classComposite, and theTail class that subclassesComponent to build the snake.
Building the Snake Head
The head of the snake will be the root node of the snake’s composite structure. Each
component of the snake will consist of a line 20 pixels in length. Example 6-13
shows theHeadclass, which draws the head of the snake. The constructor receives a
color parameter that represents the color of the snake’s head.
Example 6-12. Composite.as
package
{
public class Composite extends Component
{
protected var aChildren:Array;
public function Composite( )
{
this.aChildren = new Array( );
}
override public function add(c:Component):void
{
aChildren.push(c);
c.setParent(this);
}
override public function getChild(n:int):Component
{
if ((n > 0) && (n <= aChildren.length))
{
return aChildren[n-1];
} else {
return null;
}
}
override public function update( ):void
{
for each (var c:Component in aChildren)
{
c.update( );
}
}
}
}