Game Development Reference
In-Depth Information
Now we are ready to use the technical Java 8 class and method information that we
have learned over the past several pages of the chapter to create the core collision de-
tection logic using only around a dozen lines of Java code. We'll add another dozen
lines of code before the end of the chapter, to process the collision for our game play.
OverridingtheAbstractHeroClass:.col-
lide() Method
Finally the time has come to override and implement the public boolean collide (Act-
or object) method that we installed in our abstract Hero class back in Chapter 8 . This
is a critical method to our game play, as it determines when our primary InvinciBagel
character comes into contact with other elements in the game. The result of this contact
is scoring, as well as things changing visually on the game screen, so it becomes
pivotal to everything that we will be doing in the next chapter to implement game play
elements into the InvinciBagel game. The first thing we want to do is to install a
Boolean “flag” variable called collisionDetect , and set it equal to a false value (colli-
sion not detected) at the top of the .collide() method. The Java code for this statement
setting up the collisionDetect flag should look like the following:
boolean collisionDetect = false;
The next step in determining if a collision has occurred is to use a Java conditional
if() statement. This allows us to test if the ImageView Node objects that contain the
sprite Image assets have intersected by using the Node class .intersects() method call in
conjunction with the .getBoundsInParent() method call off of each spriteFrame
ImageView Node object. The first spriteFrame.getBoundsInParent() method call is the
one that we method chain the .intersects() method call off of, since what we are trying
to do is to ascertain collision with our primary game character. Since we want to refer-
ence the invinciBagel object (InvinciBagel class) and its iBagel Actor object, this con-
struct would take the form of an invinciBa-
gel.iBagel.spriteFrame.getBoundsInParent().intersects() method call structure.
Since the Bounds object from the Actor object that we are testing for collision needs to
be inside of the .intersects(Bounds localBounds) method call, we need to use the .getS-
priteFrame() method call we developed in Chapter 8 . Off of the Actor object we pass
into the .collide() method we will method chain the .getBoundsInParent() method call,
resulting in the object.getSpriteFrame().getBoundsInParent() structure, which is
Search WWH ::




Custom Search