
One of the absolute joys of Scratch is that you can check if one Sprite is
touching another using the sort of code shown to the right.
As always, things aren't quite so simple in Javascript but we'll make a function to help.
This may look a bit overwhelming at first, but the joy of functions is that you can either choose to accept it as a piece of magic that works, or look inside it and understand how it works.
It's a general purpose, reusable function. This means we can copy and paste it into all our projects and use it for checking if any two images are touching.
function ImagesTouching(x1, y1, img1, x2, y2, img2) {
if (x1 >= x2+img2.width || x1+img1.width <= x2) return false; // too far to the side
if (y1 >= y2+img2.height || y1+img1.height <= y2) return false; // too far above/below
return true; // otherwise, overlap
}
The upshot of this function is:
- I've made a function I've chosen to call ImagesTouching
- It accepts the x and y, and image variable for two different objects
- If either one of the objects is too far to the left of the other, they're not touching
- If either one of the objects is too far above the other, they're not touching
- If neither of the above is true, then they must be touching
Now we'll make use of that function to keep score.