if they overlap, hitTestRectangle
will return true
. You can use hitTestRectangle
with an if
statement to check for a collision between two sprites like this:
if (hitTestRectangle(cat, box)) {
} else {
//There's no collision
As you’ll see, hitTestRectangle
is the front door into the vast universe of game design.
You’ve already seen all the code that creates all these elements, as well as the keyboard control system that makes the cat move. The only new thing is the way hitTestRectangle
is used inside the play
function to check for a collision.
message.text = "Hit!";
The color of the box is then changed from green to red by setting the box’s tint
property to the hexadecimal red value.
If there’s no collision, the message and box are maintained in their original states:
message.text = "No collision...";
But what about the hitTestRectangle
function? What does it do, and how does it work? The details of how collision detection algorithms like this work is a little bit outside the scope of this tutorial. (If you really want to know, you can find out how this book.) The most important thing is that you know how to use it. But, just for your reference, and in case you’re curious, here’s the complete function definition. Can you figure out from the comments what it’s doing?