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-29. Add integer variables at the top of the Enemy.java class; set attackCounter=0, and attackFrequency=250<br />

Now we are ready to start to put a half dozen fairly complicated methods into place in the Enemy.java class.<br />

These will use the GamePlayLoop class’s .handle() method, to tap into the <strong>Java</strong>FX 60 FPS pulse timing event engine,<br />

to drive a fully automated, fully randomized Enemy attack. The code that we’ll be putting together during the<br />

remainder of this chapter is the equivalent of turning the computer processor into our game player’s opponent. Let’s<br />

write code!<br />

The Foundation of an Enemy Class Attack: The .update() Method<br />

Let’s start by writing the foundation of our iBeagle Enemy auto-attack engine. The first thing that we want to do<br />

is to “throttle” the 60 FPS pulse engine, and make sure that attacks only happen every four seconds. This is done<br />

using the attackCounter and attackFrequency variables inside of an if() structure, which counts between the two<br />

variables. If the attackCounter reaches 250, it is reset to 0 and an initiateAttack() method is called. Otherwise (else)<br />

the attackCounter is incremented using +=1. You could also use attackCounter++ to accomplish this. The code for<br />

the basic conditional if() structure, which can be seen highlighted in the middle of Figure 17-30, should look like the<br />

following <strong>Java</strong> method:<br />

public void update() {<br />

if(attackCounter >= attackFrequency) {<br />

attackCounter=0;<br />

initiateAttack();<br />

} else {<br />

attackCounter+=1;<br />

}<br />

}<br />

418<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!