I am trying to make an asteroid game with a ship and asteroids. I’ve made an asteroid array, “asteroids”, but when I run a for loop to “.update()” the movement of the asteroids, there is an error in the console. The animation still works.
function start(){
for (i=0; i<10; i++){
let radius=25
let x=Math.random()*(innerWidth-radius*2)+radius
let y=Math.random()*(innerHeight-radius*2)+radius
let dx=(Math.random()-0.5)*8
let dy=(Math.random()-0.5)*8
asteroids.push(new Asteroid(x,y,dx,dy,radius))
}
animate()
}
function animate(){
requestAnimationFrame(animate);
ctx.clearRect(0,0, innerWidth, innerHeight)
for (i=0;asteroids.length;i++){
asteroids[i].update();
}
}
function Asteroid(x,y, dx, dy, radius){
this.x=x;
this.y=y;
this.dx=dx;
this.dy=dy;
this.radius=radius
this.draw = function (){
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2, false);
ctx.strokeStyle='red';
ctx.stroke()
}
this.update= function(){
if (this.x + this.radius>innerWidth||this.x -this.radius<0){
this.dx=-this.dx;
}
if (this.y + this.radius>innerHeight||this.y -this.radius<0){
this.dy=-this.dy;
}
this.x+=this.dx;
this.y+=this.dy;
this.draw()
}
}```
The canvas is being set in the HTML:
```let canvas=document.getElementById('space')
let ctx = canvas.getContext('2d')
canvas.height=window.innerHeight
canvas.width=window.innerWidth```
I've been working with multiple .js files and have worked the error down to the above single file. The animation in HTML canvas still works and move functionality for the ship still works. Am I just over thinking the error and should just roll with it since the animation works?