I am a beginner in canvas animation, I have tried a simple example code to do a circle collision test. Before that I have tried to search around internet but I can not understand what is the logic behind. Below is the code what i get so far, the problem is some of the circle they did the collision but after that they stick together or become overlay each other, not sure if anything I have missed or wrong in the logic behind?
window.requestAnimationFrame= (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback){ window.setTimeout(callback, 1000 / 60); }; })(); (function(){ var c= document.getElementsByTagName('canvas')[0], can= c.getContext('2d'), ppl= [], count= 20; function resize(){ c.width= window.innerWidth, c.height= window.innerHeight, can.fillStyle='#000000', can.fillRect(0,0,c.width,c.height) } function pplD(){ var tf,pplnew={ x: Math.floor(Math.random()*c.width), y: Math.floor(Math.random()*c.height), size: 20,//Math.random()*4+8, vx: (Math.random()-0.5)*4+2, vy: (Math.random()-0.5)*4+2 } for(var i=0;i<ppl.length;i++){ tf= coli(pplnew,ppl[i]); if(tf){ pplD(); return } } return pplnew; } function canF(){ for(var i=0;i<count;i++){ ppl.push(new pplD) } requestAnimationFrame(render) } function coli(a,b){ var dis= a.size+b.size, disx= (a.x-b.x), disy= (a.y-b.y), disxy= Math.sqrt((disx*disx)+(disy*disy)), c; if(disxy<dis){ if((a.vx>0 && b.vx>0) || (a.vx<0 && b.vx<0)){ c= a.vx, a.vx= b.vx, b.vx= c }else{ a.vx*= -1, b.vx*= -1 } if((a.vy>0 && b.vy>0) || (a.vy<0 && b.vy<0)){ c= a.vy, a.vy= b.vy, b.vy= c }else{ a.vy*= -1, b.vy*= -1 } return true; } return false; } function drawppl(d,p){ var tf; for(var i=0;i<ppl.length;i++){ if(i==p) continue; tf= coli(d,ppl[i]); } if(d.x+d.size>c.width || d.x-d.size<0) d.vx=d.vx*-1; if(d.y+d.size>c.height || d.y-d.size<0) d.vy=d.vy*-1; d.x+= d.vx, d.y+= d.vy; can.fillStyle= '#a6e22e'; can.beginPath(); can.arc(d.x, d.y, d.size, 0, Math.PI*2, true); can.closePath(); can.fill() } function render(){ can.fillStyle='rgba(0,0,0,0.2)', can.fillRect(0,0,c.width,c.height) for(var i=0;i<ppl.length;i++){ drawppl(ppl[i],i) } requestAnimationFrame(render) } window.onresize= resize; resize(); canF() })(); html,body { width:100%; height:100%; margin:0; padding:0; border:0; } <canvas></canvas>