Collistion Simulation

Collistion Simulation

by hugogo7646

HTML

Click mouse to create more balls.
<canvas></canvas>

CSS

canvas {
  display: block;
  width: 100%;
  height: 100%;
  border: 1px solid blue;
}

JavaScript

//Class definition - Start
function Ball(x, y) {
  this.x = x;
  this.y = y;
  this.r = 10;
  this.vx = 0; //Math.random(10);
  this.vy = 0; //Math.random(10);
  this.ax = 0;
  this.ay = g;
  this.color_R = Math.round(Math.random() * 255);
  this.color_G = Math.round(Math.random() * 255);
  this.color_B = Math.round(Math.random() * 255);
}
Ball.prototype = {
  draw: function() {
    this.vx += this.ax;
    this.vy += this.ay;       
    this.x += this.vx;
    this.y += this.vy;

		//if ball hit with border
    if (isTopWallCollision(this)) {
    	this.y = this.r;
    	this.vy *= -1 * restitutionCoefficient_of_border
    }
    if (isBottomWallCollision(this)) {
    	this.y = canvas.height - this.r;
    	this.vy *= -1 * restitutionCoefficient_of_border
    }
    if (isLeftWallCollision(this)) {
    	this.x = this.r;
    	this.vx *= -1 * restitutionCoefficient_of_border
    }
    if (isRightWallCollision(this)) {
    	this.x = canvas.width - this.r;
    	this.vx *= -1 * restitutionCoefficient_of_border
    }
    
    context.beginPath();
    context.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
    context.fillStyle = 'rgba(' + this.color_R + ', ' + this.color_G + ', ' + this.color_B + ', 1)';
    context.fill()
  }
}
//Class definition - End

//Config - Start //
var ballCount = 30;
var ballList = [];
var g = 0.1;
var restitutionCoefficient_of_border = 0.9;
var restitutionCoefficient_of_ball = 0.5;
//Config - End //

var canvas = document.querySelectorAll("canvas")[0];
var context = canvas.getContext("2d");

//Create balls
for (var i = 0; i < ballCount; i++) {
  var isNewBallCollision = false;
  var newBall;
  do {
    newBall = new Ball(Math.random() * canvas.width, Math.random() * canvas.height);
    isNewBallCollision = isWallCollision(newBall);
    if (isNewBallCollision){
    	continue;
    }
    for (var j = 0; j < ballList.length; j++) {
      isNewBallCollision = isBallCollision(ballList[j], newBall);
      if (isNewBallCollision) {
        break;
    ...