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 12 ■ Setting Boundaries for Your Action Figure in 2D: Using the Node Class LocalToParent Attribute<br />

Further Modularization of the .update() Method: .setXYLocation()<br />

You might think that the KeyEvent handling Boolean variables need to be processed inside of the .update() method,<br />

but since they are simply evaluated and then increment the Bagel object’s iX and iY properties, this can be placed into<br />

its own .setXYLocation() method as well, leaving us with only top-level method calls inside of our .update() method.<br />

This will make further sprite manipulation and game play development much more organized, and will also help us to<br />

see what code is being performed at what stages in the .update() cycle. What we are going to do, which is also shown<br />

in Figure 12-14, is to create a .setXYLocation() method, which we will call first in our .update() method, and then place<br />

the four conditional if() statements inside of this new private void setXYLocation(){...} method structure. The<br />

new three method structure for our Bagel.java class .update() “chain of command” will utilize the following <strong>Java</strong> code:<br />

public void update() {<br />

setXYLocation();<br />

moveInvinciBagel(iX, iY);<br />

}<br />

private void setXYLocation() {<br />

if(invinciBagel.isRight()) { iX += vX }<br />

if(invinciBagel.isLeft()) { iX -= vX }<br />

if(invinciBagel.isDown()) { iY += vY }<br />

if(invinciBagel.isUp()) { iY -= vY }<br />

}<br />

private void moveInvinciBagel(double x, double y) {<br />

spriteFrame.setTranslateX(x);<br />

spriteFrame.setTranslateY(y);<br />

}<br />

Figure 12-14. Create a .setXYLocation() method, install four if() statements inside it, and call it from .update() method<br />

Next, we need to put some code in place that prevents our InvinciBagel character from going off of the screen, in<br />

case our game player does not reverse his direction in time. Later when we implement scoring, we could add in code<br />

that subtracts points for going “out of bounds,” but for now we are simply going to stop the movement, as if there was<br />

an invisible barrier in place at the edges of the game play area (the Stage and Scene size boundaries).<br />

266<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!