Game Development Reference
In-Depth Information
The
Animation
class follows a very basic strategy. It maintains the previous and next
key frame objects, takes the elapsed time, gets the frame in which the elapsed time
falls, and then interpolates between the values of the frame using the elapsed time.
For example, if the elapsed time is 0.5, frame two has time stamp 0.4, frame three has
time stamp 0.6, the value of pos.x equals 10 in frame two and value of pos.x equals
20 in frame three; then, it sets the bone's position using the formula:
scale=(currentTime-prevKeyTime)/(nextKeytime-prevKeyTime)
pos.x=prevKey.x+(nextKey.x-prevKey.x)*scale
=~10+(20-10)*(0.5-.4)/(0.6-0.4)
The preceding code is an example of linear interpolation as the value of
x
is a direct
function of time (scale).
The constructor of
Animation
takes two parameters, the name of the
RiggedMesh
object and the name of the animation data to play. It then retrieves the bone
hierarchy using the
parse
function of
AnimationHandler
as well as the animation
data using its
get
function.
Animation = function ( root, name) {
this.root = root;
this.data = AnimationHandler.get( name );
this.hierarchy = AnimationHandler.parse( root );
this.currentTime = 0;
this.timeScale = 1;
this.isPlaying = false;
this.isPaused = true;
this.loop = true;
};
The
play
function initializes parameters such as
isPlaying
to
true
and
isPaused
to
false
. It creates the animation cache that basically holds the
nextKey
and
preyKey
values for all bones in the mesh. It iterates over all bones and if the animation cache
is not defined for the bone, it gets the data (
pos
,
rot
, and
scale
) from the first key
(
prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
) and the second key
(
nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
) from the animation
data and stores its
prevKey
and
nextKey
variables. It then adds the
Animation
object itself to the
playing
list of the animation handler (
AnimationHandler.
addToUpdate( this );
) as shown in the following code snippet:
Animation.prototype.play = function ( loop, startTimeMS ) {
if ( this.isPlaying === false ) {
this.isPlaying = true;
this.loop = loop !== undefined ? loop : true;