I have a bit of HTML that is supposed to bounce ball(s) around the canvas, but the arrays storing the coordinates seem to be 'NaN' when I set them to a random position and test with alert("Co-ordinates " + (cirX[i]) + " x " + (cirY[i]));
. This returns 'Co-ordinates NaN x NaN'. I have tried to do it with one ball without the arrays and it worked. I am not sure if I am coding my arrays badly or if it is something else. Here is 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 have looked up how to initialise arrays e.c.t, but I seem to be doing it right? Thanks in advance for your help!
EDIT:
Despite fixing the above problems, only one ball moves and at varying speeds despite the variable ballNum
in moveBall()
varying from 0 to 2 as expected (tested by adding alert(ballNum)
). Does anyone know why?