Stick collisions



We have the beaver hopping, we have the sticks displaying - we just need to bring the two together. We want to know whenever our beaver manages to get right over a stick, so that we can count that as a successful stick grab. That means we need to do a basic collision check of the two objects. There's a lot of places we could program this functionality, since it deals with two objects - as a global function, as a method on the Stick object, as a method on the Beaver object. Let's stick it on the beaver for now:

Beaver.prototype.checkForStickGrab = function(stick) { // if beaver is over stick, do something };

In that function, we first need to write a condition that will be true if the beaver and stick collided, and false otherwise. We could make it complex or
strict, based on the location of the beaver's hand, for example, but let's stay basic for now. They should "collide" if:

• The stick's center x position is between the two sides of the beaver.
• The stick's center y position is between the top and bottom of the beaver.
The stick is drawn using the rect command, so typically, that would mean that its x and y properties represented its upper left corner coordinates. However,
to simplify our collision calculation, we can switch to a mode where the rect is drawn from the center:

rectMode(CENTER);
rect(this.x, this.y, 5, 40);

The image for the beaver is also drawn by default from the upper left corner, but we'll keep that mode, as it works well for our calculation. To check the
first condition, on the x position, we can do a check like this, where we check that the stick x is greater than or equal to the beaver's left side (x) and
less than or equal to the beaver's right side (x + 40)
stick.x >= this.x && stick.x <= (this.x + 40)

To check the y position, we can do a similar check, where we see if the stick y is greater than or equal to the beaver's top (y) and less than or equal to the beaver's bottom (y + 40):

stick.y >= this.y && stick.y <= (this.y + 40)

Now, what should we actually do, once we've detected a collision between the beaver and the stick? We effectively want to remove the stick from the screen and prevent further collision. One simple way to do that is to just push the stick way off screen, by changing its y coordinate:

stick.y = -400;

At the same time, we want to remember how many sticks the beaver has "grabbed", so we'll increment the internal sticks property:

this.sticks++;

Finally, we need to call this method at an opportune time- how about right after we've drawn each stick?

for (var i = 0; i < sticks.length; i++) {
sticks[i].draw();
beaver.checkForStickGrab(sticks[i]);
sticks[i].x -= 1;
}

Here it is all together - check it out, when you hop over the sticks, they disappear!