Game Development Reference
In-Depth Information
As you can see, we set the animation to initially show the first frame, and we initial-
ize the
time
variable to zero (more about that later).
26.4.1 Updating the Animation that Is Currently Playing
In the
Update
method, we have to calculate which frame should be drawn. But that
means that we need to know how much time has passed since the last frame was
drawn. If we were to increment the frame index in every call to the
Update
method,
the animation would be played way too fast. So, we will save the time that has
passed since the last frame was drawn inside the member variable
time
.Wehaveto
update this variable in the beginning of the
Update
method:
time += (
float
)gameTime.ElapsedGameTime.TotalSeconds;
We are using the property
ElapsedGameTime
here, which indicates how much time
has passed since the last time
Update
was called. This property gives us an object
of type
TimeSpan
which in turn has a property called
TotalSeconds
that expresses the
elapsed time, in seconds, as a
double
.
Now we can calculate the index of the frame that should be shown. For this, we
will use a
while
-instruction:
while
(time > frameTime)
{
−
= frameTime;
if
(isLooping)
sheetIndex = (sheetIndex + 1) %
this
.NumberSheetElements;
else
sheetIndex = Math.Min(sheetIndex + 1,
this
.NumberSheetElements
time
−
1);
}
What happens here exactly? The
while
-instruction continues as long as the
time
vari-
able contains a value larger than
frameTime
. Inside the
while
-instruction, we sub-
tract the frame time from the
time
variable. Suppose that the time that each frame
is displayed is set to 1 second. Now we enter the
Update
method and we add the
elapsed time to the
time
member variable. Suppose that this variable now contains
the value
1.02
, meaning that the frame we are currently showing has been shown for
1.02 seconds. This means that we should show the next frame instead. We do this by
incrementing the index of the frame we are currently showing. We then update the
time
variable and subtract the frame time (1 second), so that the new value of
time
becomes 0.02. We have put this code inside a
while
-instruction, so that we are sure
that we always show the right frame, even if the time passed since the last update
was multiple times the frame time. For example, if the new value of
time
was 3.4,
then we would need to move three frames ahead and subtract the frame time three
times from the
time
variable. The
while
-instruction takes care of that.