Learn Create Your Own Split Screen

Next Page

It works pretty well, but if you play around with it a bit you'll notice it suffers a slight failing many of our other games have too.

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.

function ImagesTouching(thing1, thing2, margin) { // // This function detects whether two MySprites are touching - very useful function // // 'margin', if provided, specifies how much overlap is allowed before they are considered to have touched // if (!margin) margin = 0; if (!thing1.visible || !thing2.visible) return false; if (!thing1.w || !thing2.w) return false; if (thing1.x >= thing2.x + thing2.w - margin || thing1.x + thing1.w <= thing2.x + margin) return false; if (thing1.y >= thing2.y + thing2.h - margin || thing1.y + thing1.h <= thing2.y + margin) return false; return true; }

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.