Game Development Reference
In-Depth Information
Step 4. The current version of the code allows the character to walk
around the environment. Let's add some code to fire the character's
gun. Add the lines shown in Listing 3.24 .
Step 5. Play. It appears as though nothing happens when the
space bar is pressed. However, note that “Firing” is being printed
in the console, which proves that the if statement is being
executed. If you press the space bar a bunch of times and watch
the character closely you may see it flinch. So what is happening?
The ShootStraight animation starts to run, but before many or any
frames play, the Update() function runs again; if the character is
not moving, the animation gets set to Idle before ShootStraight
has finished playing. This is a common issue in managing
animations.
Step 6. To fix this issue in the past, a programmer would have to write
code to test if one animation has finished playing before another
starts. This can still be done; however, in this case, Unity provides
a very neat way for giving priority to animations—layers. Each
animation can be assigned a layer. Animations in higher level layers
have a higher priority, and lower level animations cannot interrupt
their frames. Modify the Start() function of animationManagement
script to that shown in Listing 3.25 .
Listing 3.25 Placing All Animations Except Shooting
into a Lower Layer
function Start()
{
//loop all animations unless otherwise set
this.animation.wrapMode = WrapMode.Loop;
this.animation["Idle"].layer = -1;
this.animation["WalkForward"].layer = -1;
this.animation["WalkBackward"].layer = -1;
//don't loop shooting animation
this.animation["ShootStrai ght"].wrapMode =
WrapMode.Clamp;
this.animation.Stop();
}
Step 7. This new code will place the idle and walking animations
in layer - 1. By default, all animations are in layer 0. This means
the shooting animation will remain in 0 and be given priority
over those in - 1. In addition, animations in layer - 1 are cyclic and
therefore set to loop. We don't want the shooting animation to
loop; therefore, it is set to clamp, which plays it once and stops.
Because the shooting animation is in a higher layer, when it is set
to play, it becomes visible on the screen while the other animations
take a back seat. When the shooting animation reaches the end and
 
Search Nedrilad ::




Custom Search