28.04.2019 Views

[JAVA][Beginning Java 8 Games Development]

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 17 ■ Enhancing Game Play: Creating a Scoring Engine, Adding Treasure and an Enemy Auto-Attack Engine<br />

Figure 17-36. Add callAttack, spriteMove and destination variables and an if(callAttack)-else programming structure<br />

The first thing that we’ll need to do, inside the .update() method, is add an if(!callAttack) if-else conditional<br />

structure around the if(attackCounter >= attackFrequency) structure that we already have in place. We will leave<br />

the attackCounter = 0; initialization statement inside of this inner loop, and we will add a spriteMoveR = 700;<br />

and a spriteMoveL = -70; initialization statement. These will place the Enemy sprite off-screen on either side<br />

of the Stage.<br />

A callAttack boolean flag allows us to communicate between the .update() and the .initiateAttack methods, as<br />

you can see, in the .update() method, after the attackCounter (timer) has allowed the player enough time to collect<br />

his wits after enemy attacks, this callAttack variable is set to a true (attack) value. In a more complex version of your<br />

.initiateAttack() method, you will set this callAttack variable to a false (delay attack) value, starting the attackCounter.<br />

Let’s also make a <strong>Java</strong> code optimization and take the .setTranslateY() method call that we have twice in the<br />

initiateAttack() method, and make just a single method call (which represents a 100% savings on usage of the Random<br />

object’s .nextInt() method call). Once all these programming statements are in place, you can finally set the callAttack<br />

boolean variable to a true value, so that the next time that the if(!callAttack) conditional if-else structure is called, the<br />

else portion at the bottom of the structure will execute and will call an initiateAttack() method. This method is where<br />

the real heavy lifting is done, as far as animating the iBeagle Enemy character onto the screen, having him pause<br />

and fire off a shot, and then retreat off-screen before the InvinciBagel can execute (collide with) him, gaining ten<br />

valuable scoring points.<br />

The else part of this if-else programming structure will call the initiateAttack() function, once the callAttack<br />

variable has been set to a true value inside of the attackCounter timer section of your conditional programming logic.<br />

www.it-ebooks.info<br />

425

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

Saved successfully!

Ooh no, something went wrong!