Example: Animating Composite Objects Using Inverse Kinematics | 223
Using Inverse Kinematics
Inverse kinematics is a method by which rigid objects interconnected by joints can
move to form different poses. A good example of this type of object is a marionette: a
puppet controlled by a puppeteer using strings. The hands and legs of the puppet
consist of several parts connected by joints. For example, the upper arm would be
connected to the torso at the shoulder. The upper arm would in turn be connected to
the forearm through the elbow joint. The hand would be connected to the forearm at
the wrist. These interconnected objects form a kinematic chain. Inverse kinematics
allows kinematic chains to move, constrained by the range of motion allowed by the
joints. The simplest form of a kinematic chain has a free end that’s controlled exter-
nally. For example, the hand of a marionette would be a free end since it’s attached
to a puppeteer’s string. Because joints connect them, the hand, forearm, and upper
arm move when the puppeteer pulls this string. Try this yourself: let your left arm go
limp, and pull it up by the hand using your right arm. Notice how the external force
is pulling your left hand, which translates the pulling motion to the forearm, which
in turn pulls the upper arm. The notion of interconnected objects pulling each other
is the primary concept in inverse kinematics. This type of motion is very similar to
the motion of the snake application we will develop.
In the example application, users will control the head of the snake using the key-
board. When the head moves, interconnected body segments will move based on
inverse kinematic principles. The whole snake will be a kinematic chain.
Kinematic chains consist of one or more kinematic pairs. For example, the upper
arm and forearm form a kinematic pair. Adjoining body segments in our snake will
also form kinematic pairs. We will develop the snake as a composite object. The
head of the snake will be the root node, and body segments will be connected to
each other. Each node will be a composite object as they have child objects con-
nected to them. The last segment of the snake, which is the tail (or the rattle for a
rattlesnake), will be a component object.
Creating Component and Composite Nodes for the Snake
All our components will bedisplay objectson the stage. Therefore we can develop the
component class by extending theSpriteclass. This allows us to inherit the proper-
ties and methods to manipulate components on the stage to make them move and
respond to events. Example 6-11 shows theComponentclass that’ll be used to create
animated figures. The only difference in this class when compared to previous com-
ponent classes is that it extends theSpriteclass and declares a method called
update( ).