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 16 ■ Collision Detection: Creating SVG Polygons for the Game Actors and Writing Code to Detect Collision<br />

Figure 16-40. The finished .collide() method is error-free and only 19 lines of code, and is ready for further optimization<br />

If you use a Run ➤ Project work process, and test your game code now, you will not only hear the audio, you will<br />

also see the Prop objects disappear upon collision with the InvinciBagel object. I’m going to leave the audio in this<br />

code for now, so you can test to see if these Actor objects are really gone by have the InvinciBagel run (or fly) over the<br />

area where the Prop object was to make sure (using your ears) that it’s really gone. Next, we’ll optimize the code even<br />

more, by implementing the if(collide(object)) approach that I mentioned earlier, having the .collide() method simply<br />

return a true (collision detected) or false (no collision detected) value, as a properly behaved Boolean method should.<br />

Optimizing Collision Detection Processing: if(collide(object))<br />

To optimize the collision detection process, we’ll move code that is executed on collision up to the .checkCollision()<br />

method, inside of an if(collide(object)){} conditional if block of <strong>Java</strong> code. This allows us to eliminate a Boolean<br />

collisionDetect variable from the collide() method, making it much more streamlined. All we are doing now in the<br />

.collide() method is pass the return true; statement back up to the calling entity, in this case, the .checkCollision()<br />

method, if a collision is detected. This also allows us to completely eliminate the if(collisionDetect) structure as well.<br />

Before this optimization, we had 6 lines of code in the .checkCollision() method, and 19 lines of code in the<br />

.collide() method. After the optimization, we have 5 less lines of <strong>Java</strong> code, with 10 lines of code in each method. The<br />

new <strong>Java</strong> structures for these methods are error-free, as shown in Figure 16-41, and look like the following <strong>Java</strong> code:<br />

public void checkCollision() {<br />

for(int i=0; i

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

Saved successfully!

Ooh no, something went wrong!