Because we're doing bounding-box collision detection (where we just look for any overlap between the image rectangles), sometimes we get a 'touch' detected when it's really just a glancing encounter.
Some game software has the idea of a "hit box" -- a different rectangle that defines which part of the image is considered a touch or not.
What we'll do is alter our ImagesTouching function so it also accepts a "margin" parameter. If supplied, we'll use some simple arithmetic to say that the rectangles have to overlap by at least that much before it's considered a hit.
When we check for the hero touching the fruit, we'll specify a margin of 10, so the spider has to overlap by 10 pixels before it's considered a touch.
As well as involving the margin in all the overlap calculations, we include a line to say if there is no margin (it wasn't supplied), then treat it as zero.
We've also enhanced the function to say if either of the sprites don't have a width yet (they haven't finished loading yet), then never consider them to have touched. This makes the function work more reliably during the first few moments our program runs.
|