HTML and CSS Reference
In-Depth Information
Collision-based distribution
There are times when you might want objects distributed randomly within a particular shape or shapes.
Perhaps the easiest way to accomplish this is to generate a random position on the screen, and use some
collision testing to determine whether this point falls within a certain area of the screen. If the point is
outside the shape, then discard it and generate a new random screen position, which we again test. Keep
doing this process until you find a point that falls within the specified area.
In the next example, we distribute the dots randomly within two circles, which we reference using our Ball
class. We use the distance-based collision detection formula from Chapter 9 to determine whether the dot
falls within either of the two balls. And if it doesn't, keep trying until we find one. This example can be
found in 10-random-8.html :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Collision-Based Distribution</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="utils.js"></script>
<script src="ball.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
numDots = 300,
ball0 = new Ball(),
ball1 = new Ball(80);
ball0.x = 100;
ball0.y = canvas.height / 2;
ball1.x = 300;
ball1.y = canvas.height / 2;
function detectCollision(x, y, ball) {
var dx = x - ball.x,
dy = y - ball.y,
dist = Math.sqrt(dx * dx + dy * dy);
return (dist < ball.radius);
}
while (numDots--) {
//initialize variables
var x = 0,
y = 0;
//if x, y not in ballA AND not in ballB, set new random position
while (!detectCollision(x, y, ball0) && !detectCollision(x, y, ball1)) {
//get random position on canvas
 
Search WWH ::




Custom Search