HTML and CSS Reference
6.3.2. Detecting overlap
In simple 2D games, you create collisions by testing for object overlap. These checks occur
each time the interval refreshes and draws an updated set of objects. If an object is over-
lapping another, some logic that causes a response is activated. For instance, if a ball and
paddle overlap, then one object should repel the other.
What about real game physics?
Sad to say, we're teaching you only how to detect overlapping shapes, which isn't real
physics integration. Physics in programming is a complicated subject that we could easily
fill a hundred topic with and still have more to write about. If you're interested in learning
how to make games more lifelike, please see Glenn Fiedler's robust article on game physics
You'll start building collisions detection into Canvas Ricochet by keeping objects con-
tained inside the play area. After taming objects, you'll focus on using the paddle to bounce
the ball at the bricks. Once the ball is bouncing back, you'll configure ball-to-brick overlap
logic. When that's done, you'll create rules to determine when the game shuts down. Let's
Step 3: Enable edge detection for the paddle and ball
To prevent your ball and paddle from flying offscreen, check them against the <canvas>
DOM element's width and height stored in Game.width and Game.height .
Go to your Paddle.move() method and replace its contents with the following snippet,
which checks to see if the paddle has a positive x coordinate and is within the play area's
width. If it is, then Paddle.x updates as normal; otherwise, it stops halfway into the right