Bouncing ball in rectangle using D3js
Simple Bouncing Balls in rectangle using D3js
HTML
<h2>
Simple Bouncing Balls in rectangle using D3js - by Atul
</h2>
<div id="mainDiv" style="width:850px; height:500px">
<div id="drawAreaOuter" style="width:100%; height:100%; ">
<div id="menuTop" >
<a id="startStop" style="font-size:x-large" href="javascript:StartStopGame()">Start</a> |
Speed :
<select id='speed' onchange="OnSpeedChange()">
<option value="1" selected="selected">Slow</option>
<option value="3" >Medium</option>
<option value="5">Fast</option>
</select> |
Number of Balls :
<select id='numberOfBalls' onchange="OnNumberOfBallsChanged()">
<option value="5" selected="selected">6</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
</select>
</div>
<div id="drawArea" style="width:100%; height:100%; border:1px solid gray">
</div>
</div>
</div>
JavaScript
// Ball object - multiple balls can be created by instantiating new objects
function Ball(svg, x, y, id, color, aoa, weight) {
this.posX = x; // cx
this.posY = y; // cy
this.color = color;
this.radius = weight; // radius and weight same
this.jumpSize = 1; // equivalent of speed default to 1
this.svg = svg; // parent SVG
this.id = id; // id of ball
this.aoa = aoa; // initial angle of attack
this.weight = weight;
if (!this.aoa)
this.aoa = Math.PI / 7;
if (!this.weight)
this.weight = 10;
this.radius = this.weight;
this.data = [this.id]; // allow us to use d3.enter()
var thisobj = this; // i like to use thisobj instead of this. this many times not reliable particularly handling evnet
// **** aoa is used only here -- earlier I was using to next move position.
// Now aoa and speed together is velocity
this.vx = Math.cos(thisobj.aoa) * thisobj.jumpSize; // velocity x
this.vy = Math.sin(thisobj.aoa) * thisobj.jumpSize; // velocity y
this.initialVx = this.vx;
this.initialVy = this.vy;
this.initialPosX = this.posX;
this.initialPosY = this.posY;
// when speed changes, go to initial setting
this.GoToInitialSettings = function (newjumpSize) {
thisobj.posX = thisobj.initialPosX;
thisobj.posY = thisobj.initialPosY;
thisobj.vx = Math.cos(thisobj.aoa) * newjumpSize; // velocity x
thisobj.vy = Math.sin(thisobj.aoa) * newjumpSize; // velocity y
thisobj.Draw();
}
this.Draw = function () {
var svg = thisobj.svg;
var ball = svg.selectAll('#' + thisobj.id)
.data(thisobj.data)
;
ball.enter()
.append("circle")
.attr({"id" : thisobj.id, 'class' : 'ball', 'r' : thisobj.radius,...