Amazon.com Widgets

Agile Otaku

Bouncing a Ball with HTML 5, a Primer for a Slingshot game

Im still reading the book The Essential Guide to HTML5. Now It is teaching how to bounce a ball. Unfortunately, I did not like its solution of a bouncing ball, so I looked around for a better solution, I saw in the sample code of the book Introducing HTML5 about a better implementation, so I incorporated it with my sample code. I want to build on this example so that I can somehow simulate a slingshot like what the Angry Bird game does.

First, is the formula for bouncing a ball

//if the x coordinate is greater than the boundary, reverse the direction
if (x + dx > (WIDTH-dia) || (x + dx < 0))
    dx = -dx;
//if the y coordinate is greater than the boundary, reverse the direction
if (y + dy > (HEIGHT-dia) || (y + dy < 0))
    dy = -dy;

//if the y had gone past it usage, stop using it
if(y>(HEIGHT-dia)) {
    dy = 0;
}
else {
    //this simulates the bouncing, decrease the bounce each time until it goes to none
    dy += 3;
    //use the new differential
    y += dy;
}
//use the new differential
x += dx;

What you saw in the code above, is the most important part for simulating a bouncing ball, there are actually plenty of examples in the web using to bounce a ball using html5, but this is the only one I saw so far that has decreasing height of bounce.

Next we need the standard drawing stuff such as drawing a circle, and clearing after a specific interval

var clearCircle = function(){
    ctx.clearRect(0, 0, WIDTH, HEIGHT);
}

var drawCircle = function(){
    ctx.beginPath();
    ctx.arc(x, y,dia/2,0,Math.PI*2, false);
    ctx.closePath();
    ctx.fill();
}
var drawEngine= function(){
    clearCircle();
    drawCircle();
    adjustPath();
};
window.clearInterval(_timer);
_timer = window.setInterval(drawEngine, 10);

After this, our bouncing ball is complete.

The resulting path is like the one below

View the live demo here

Comments