HTML and CSS Reference
In-Depth Information
Applying Collision Detection
Wewillbecheckingtheboundingboxaroundeachobjectwhenwedoourcollisiondetection.
A bounding box is the smallest rectangle that will encompass all four corners of a game logic
object. We have created a function for this purpose:
function
function
boundingBoxCollide
(
object1
,
object2
) {
var
var
left1
=
object1
.
x
;
var
var
left2
=
object2
.
x
;
var
var
right1
=
object1
.
x
+
object1
.
width
;
var
var
right2
=
object2
.
x
+
object2
.
width
;
var
var
top1
=
object1
.
y
;
var
var
top2
=
object2
.
y
;
var
var
bottom1
=
object1
.
y
+
object1
.
height
;
var
var
bottom2
=
object2
.
y
+
object2
.
height
;
iif
(
bottom1
<
top2
)
return
return
(
false
false
);
iif
(
top1
>
bottom2
)
return
return
(
false
false
);
iif
(
right1
<
left2
)
return
return
(
false
false
);
iif
(
left1
>
right2
)
return
return
(
false
false
);
return
return
(
true
true
);
};
We can pass any two of our game objects into this function as long as each contains
x
,
y
,
width
,and
height
attributes.Ifthetwoobjectsareoverlapping,thefunctionwillreturn
true
.
If not, it will return
false
.
The
checkCollision()
functionfor
GeoBlasterBasic
isquiteinvolved.Thefullcodelisting
isgivenin
Example 8-12
.
Ratherthanreprintithere,let'sexaminesomeofthebasicconcepts.
One thing you will notice is the use of “labels” next to the
for
loop constructs. Using labels,
such as in the following line, can help streamline collision detection:
rocks
:
for
for
(
var
var
rockCtr
=
rocksLength
;
rockCtr
>=
0
;
rockCtr
--
){
We will need to loop through each of the various object types that must be checked against
one another. But we do not want to check an object that was previously destroyed against
other objects. To ensure that we do the fewest amount of collision checks necessary, we have
implemented a routine that employs label and
break
statements.
Here is the logic behind the routine: