Friday, November 16, 2012

Bouncing Ball using Array in HTML5

I want to create bouncing ball program that's very easy on Flash, Python or Delphi yet very tricky on html5. The program consist of n ball with random velocity (each) moving in a 2d box (oh yeah, square then :) ) 

I am playing with array in html5 script which is helpful on this program. I don't declare the array using

aBola = new array()

that come  as standart on many language, but prefer

aBola = []

instead, just like list on python. In this program, array's just like container for ball.

In html5, moving an object is a bit tricky and, for some Pascal programmer like me, bringing an old memory of draw-clear-draw-clear... cycle; draw a ball, delete it, draw the same ball but slightly right, delet it, ... and so on. All that kind of tedious job, but it worth for the sake of fast execution and no-need-slow-loading-flash-player thing.




Here's the code under script tag. Keep in mind that many variable's name is in indonesian (ball -> bola, bounce->pantul, collision -> tumbukan )
 
 //bola:ball
 //pantul:bounce
  var context;
  var n=10;

   // membuat bola 
   function bola(color, r,dx,dy){
      this.canvas  = canvas;
      this.context = canvas.getContext('2d');
      this.r  = r;
      this.x =Math.random()*400+30;
      this.y  = Math.random()*250+30;
      this.dx  = dx;
      this.dy  = dy;
      this.color   = color;
   }

   bola.prototype.Create = function (){
      this.context.beginPath();
      this.context.fillStyle = this.color;
      this.context.arc(this.x,this.y,this.r,0,Math.PI*2,false);
      this.context.fill();
   }
   bola.prototype.Pantul = function (){
  if (this.x >= (canvas.width - this.r) || this.x <= this.r) this.dx *= -1;
      if (this.y >= (canvas.height - this.r) || this.y <= this.r) this.dy *= -1; 
   }
   function init(){
    canvas  = document.getElementById("myCanvas")
      context = canvas.getContext('2d');
  // membuat array untuk bola
  //create array for ball
      aBola = [];
  for (i=1;i<=n;i++){
   //membuat bola sejumlah n dengan dx dan dy acak
   //create n balls with random dx and dy
   dx = Math.random()*10-5;
   dy = Math.random()*10-5;
       aBola.push(new bola('#007700', 17,dx,dy)); 
      }
         setInterval(draw,20);
   }
   function draw(){
      context.clearRect(0,0, 500,350);
  for (i in aBola) {
   //menggerakkan bola
   //moving balls
         aBola[i].x += aBola[i].dx;
         aBola[i].y += aBola[i].dy;
         aBola[i].Pantul();
         aBola[i].Create();
       }
    }

(to be continued)