I'm facing an issue with my HTML code that is supposed to make ball(s) bounce around the canvas. However, when I set the arrays storing the coordinates to random positions and test with
alert("Co-ordinates " + (cirX[i]) + " x " + (cirY[i]));
, it returns 'Co-ordinates NaN x NaN'. I tried doing it with a single ball without using arrays and it worked fine. I'm not sure if there's any mistake in how I'm coding my arrays or if it's something else. Here's my HTML:
<!Doctype HTML>
<head>
<script>
var cirX = [];
var cirY = [];
var chX = [];
var chY = [];
var width;
var height;
function initCircle(nBalls) {
alert(nBalls)
for(var i = 0; i<nBalls;i++) {
alert("loop " + i)
chX[i] = (Math.floor(Math.random()*200)/10);
chY[i] = (Math.floor(Math.random()*200)/10);
cirX[i] = Math.floor(Math.random()*width);
cirY[i] = Math.floor(Math.random()*height);
alert("Co-ordinates " + (cirX[i]) + " x " + (cirY[i]));
circle(cirX[i],cirY[i],3);
setInterval('moveBall(i)',10);
}
}
function moveBall(ballNum) {
if(cirX[ballNum] > width||cirX[ballNum] < 0) {
chX[ballNum] = 0-chX[ballNum];
}
if(cirY[ballNum] > height|| cirY[ballNum] < 0) {
chY[ballNum] = 0-chY[ballNum];
}
cirX[ballNum] = cirX[ballNum] + chX[ballNum];
cirY[ballNum] = cirY[ballNum] + chY[ballNum];
circle(cirX[ballNum],cirY[ballNum],3);
}
function circle(x,y,r) {
var c=document.getElementById("canvas");
var ctx=c.getContext("2d");
canvas.width = canvas.width;
ctx.fillStyle="#FF0000";
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.fill();
width = canvas.width;
height = canvas.height;
}
</script>
</head>
<body>
<canvas id="canvas" width="400" height="300">
</canvas>
<script>
initCircle(3); //this sets the number of circles
</script>
</body>
I've researched how to initialize arrays correctly, but it still seems like I'm doing it right? Would appreciate any help on this matter!
EDIT:
Even after fixing the above mentioned issues, only one ball moves and at different speeds despite the variable ballNum
in moveBall()
ranging from 0 to 2 as expected (confirmed by adding alert(ballNum)
). Any ideas why?