28.04.2019 Views

[JAVA][Beginning Java 8 Games Development]

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 13 ■ Animating Your Action Figure States: Setting the Image States Based on KeyEvent Processing<br />

Animating Your Run Cycle: Creating a Nested If-Else Structure<br />

The next step in our sprite animation for this chapter is to actually animate a run cycle for our character, which we<br />

would normally do with <strong>Java</strong>FX KeyFrame and Timeline classes, but which we will do here in little more than a dozen<br />

lines of code. Since we are already using the AnimationTimer class, this is the optimal approach, and can be done<br />

using only a single Boolean variable. Since we have two cels for our run cycle, we can use this Boolean variable and<br />

alternate its value between true and false. If this Boolean value, which we will call animator, is false, we will show the<br />

cel in imageStates(1), which is our starting to run position (foot touching the ground). If animator is true, we will show<br />

the cel in imageStates(2), which is our full-out run position (both feet in full motion). Create the Boolean animator<br />

variable at the top of the Bagel.java class. NetBeans was giving me a “variable not initialized” warning, so I explicitly<br />

set it equal to the default Boolean value of false, as I want the run cycle to always start with a foot pushing off of the<br />

ground. The variable declaration statement should look like the following, and is shown at the very top of Figure 13-6:<br />

boolean animator = false;<br />

Figure 13-6. Nest an if-else logic structure alternating between sprite cels 1 and 2 using the boolean animator variable<br />

Since we want the run cycle to always start with the imageStates(1) foot pushing off the ground cel, we will add an<br />

animator=false; line of code inside of our “no arrow keys pressed” code statement. This statement will now do two<br />

different things: setting the imageStates(0) waiting sprite Image reference; and making sure that the animator variable<br />

is initialized to a false value, which ensures the run cycle starts with a foot on the ground, just like it would in real life.<br />

The new <strong>Java</strong> code for the “no arrow keys pressed” conditional if() structure should look like the following:<br />

if( !invinciBagel.isRight() &&<br />

!invinciBagel.isLeft() &&<br />

!invinciBagel.isDown() &&<br />

!invinciBagel.isUp() ) {<br />

spriteFrame.setImage(imageStates.get(0));<br />

animator=false; }<br />

www.it-ebooks.info<br />

279

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!