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 8 ■ Creating Your Actor Engine: Design the Characters for Your Game and Define Their Capabilities<br />

Figure 8-13. Add initialization for your eleven variables inside of your constructor method using compound statements<br />

Before we generate our getter and setter methods, let’s take a look at how we can use a combination of compound<br />

variable declaration statements and the knowledge of what default variable type values <strong>Java</strong> will set for our variables<br />

if we do not explicitly specify them to reduce the amount of code that it takes to write the entire Hero class from its 25<br />

lines of code (or 33 if we didn’t use compound variable initialization statements) to 14 lines of code.<br />

If you don’t count lines of code with one curly brace on them (three) we are talking less than a dozen lines of <strong>Java</strong><br />

statements, including package, class and import declarations, to code this entire public abstract class. This is pretty<br />

impressive, given how much motion sprite power and capabilities the core class gives us. Of course, after we add the<br />

22 getter and setter methods, which are 3 lines of code each, we will have about 80 lines of total code, sans spacing.<br />

It is important to note that NetBeans will be writing more than 75% of this class’s code for us! Pretty cool.<br />

Optimizing the Hero Class Via Compound Statements and Default Variable Values<br />

I am going to do two major things to reduce the amount of code in this primary portion of the Hero class, before<br />

we have NetBeans write our getter and setter methods for us. The first is to use compound declaration for all of our<br />

similar data types, declaring the protected double and protected float modifiers and keywords first, and then listing all<br />

of the variables after those, separated by commas, which is called “comma delimited” in programming terms. The <strong>Java</strong><br />

code for the eleven Hero class variable declarations will now look like the following:<br />

protected double vX, vY, lifeSpan, damage, offsetX, offsetY;<br />

protected float boundScale, boundRot, friction, gravity, bounce;<br />

www.it-ebooks.info<br />

181

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

Saved successfully!

Ooh no, something went wrong!