HTML and CSS Reference
In-Depth Information
log.value = '';
}
ballA.draw(context);
ballB.draw(context);
}());
};
</script>
</body>
</html>
This example creates two instances of the Ball class and sets one of them to be dragged with the mouse.
The utils.intersects function is called on each frame to check whether the two balls are hitting. If you
approach the stationary ball from the top, bottom, or sides, it is accurate, but you always get a false
positive if you come in diagonally. If you were to try drawing some other shapes instead of a ball, you
would see that rectangular shapes work perfectly, but the more irregular the shape you use, the more
inaccuracies you'll find. Be careful about using this method for anything other than rectangular shapes.
To visualize each ball's bounding box, simply draw these rectangles to the canvas. Try adding the
following code to the end of the drawFrame animation loop:
var boundsA = ballA.getBounds(),
boundsB = ballB.getBounds();
context.strokeRect(boundsA.x, boundsA.y, boundsA.width, boundsA.height);
context.strokeRect(boundsB.x, boundsB.y, boundsB.width, boundsB.height);
Now we'll look at an exercise that demonstrates using utils.intersects with rectangles. The example
uses a new Box class that is very similar to Ball , and which I'm sure you'll have no trouble understanding.
Here it is:
function Box (width, height, color) {
if (width === undefined) { width = 50; }
if (height === undefined) { height = 50; }
if (color === undefined) { color = "#ff0000"; }
this.x = 0;
this.y = 0;
this.width = width;
this.height = height;
this.vx = 0;
this.vy = 0;
this.rotation = 0;
this.scaleX = 1;
this.scaleY = 1;
this.color = utils.parseColor(color);
this.lineWidth = 1;
}
Box.prototype.draw = function (context) {
context.save();
context.translate(this.x, this.y);
context.rotate(this.rotation);
context.scale(this.scaleX, this.scaleY);
 
Search WWH ::




Custom Search