Bounce

Bounce.html  [download]

<!DOCTYPE html>

<html>
<head>

<title>Comp 86 example</title>
<!-- Based on: http://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_building_practice -->

<script type="text/javascript">
"use strict"; //*5 Global set up

// Globals
var canvas, gc //*5
var circles = [] //*5

onload = function () {
	// Set up canvas
	canvas = document.getElementById ('myCanvas'); //*5
	gc = canvas.getContext ('2d'); //*5
	canvas.width = window.innerWidth; //*5
	canvas.height = window.innerHeight; //*5

	// Create list of circles
	for (var i=0; i<100; i++) { //*5
		circles.push(new Circle ( //*5
			random (0, canvas.width), //*5
			random (0, canvas.height),
			random (-4, 4),
			random (-4, 4),
			'rgb(' + random (0,255) + ',' + random(0,255) + ',' + random(0,255) +')',
			random (10,20)));
	}

	loop () //*6 Animation
}

function loop() { //*6
	gc.fillStyle = 'rgba(0, 0, 0, 0.2)'; //*6
	gc.fillRect(0, 0, canvas.width, canvas.height); //*6

	for (var c of circles) { //*6
		c.draw(); //*6
		c.update(); //*6
	}

	requestAnimationFrame (loop); //*6
}

class Circle { //*1 Circle class, like Square
	constructor (x, y, velX, velY, color, size) { //*2 Maintains info
		this.x = x; //*2
		this.y = y; //*2
		this.velX = velX;
		this.velY = velY;
		this.color = color;
		this.size = size;
	}

	draw () { //*3 Knows how to draw itself when told
		gc.beginPath (); //*3
		gc.fillStyle = this.color; //*3
		gc.arc (this.x, this.y, this.size, 0, 2 * Math.PI); //*3
		gc.fill (); //*3
	}

	update () { //*4 Knows how to update itself when told
		// Check if circle has hit edge of canvas
		if ((this.x + this.size) >= canvas.width) { //*4
			this.velX = -(this.velX); //*4
		}

		if ((this.x - this.size) <= 0) { //*4
			this.velX = -(this.velX);
		}

		if ((this.y + this.size) >= canvas.height) { //*4
			this.velY = -(this.velY);
		}

		if ((this.y - this.size) <= 0) { //*4
			this.velY = -(this.velY);
		}

		// Check if circle has hit another circle
		for (var c of circles) { //*7 Check for collision
			if (!(this === c)) { //*7
				var dx = this.x - c.x; //*7
				var dy = this.y - c.y; //*7
				var distance = Math.sqrt(dx*dx + dy*dy); //*7
				if (distance < this.size + c.size) { //*7
					c.color = this.color = 'rgb(' + random(0, 255) + ',' + random(0, 255) + ',' + random(0, 255) +')'; //*7
				}
			}
		}

		this.x += this.velX; //*4
		this.y += this.velY; //*4
	}
}

// Utility function, generate random integer between min and max
function random(min,max) {
	return Math.floor (Math.random() * (max-min)) + min;
}

</script>

</head>

<body>
<h1>Bouncing Circles</h1>
<canvas id="myCanvas"></canvas>
</body>

</html>