-1

I have a class called invaders which hold the properties of an image. I want to take that class, make copies of said invaders and give them a new positions which is the "this.x" and "this.y". I was able to push the class in an array and I have a loop that runs and controls the amount of enemies I want to be displayed, but I am unable to access their position in order to change it for lets the say the second invader.

I believe my loop runs fine because when I console log the length it does say the right amount so I think they are all stacked on top of each other which makes sense as I still can't figure out how to change the position for each.

let invaderCount = 5
const allInvaders = []
class Invaders{
    constructor(){
        this.x = 200
        this.y = 200
        this.width = 50
        this.height = 50
        const image = new Image();
        image.src = './image/invader.png'
        this.image = image
    }
    draw(){
        ctx.drawImage(this.image, this.x, this.y, this.width, this.height)
    }
    update(){
        this.draw()
    }
}
const invaders = new Invaders()
for(let i=0; i < invaderCount; i++){
    allInvaders.push(invaders)
}
console.log(allInvaders.length)
function animate(){

    requestAnimationFrame(animate)

    invaders.update()

}
animate()
  • Does this answer your question? [How to clone a javascript ES6 class instance](https://stackoverflow.com/questions/41474986/how-to-clone-a-javascript-es6-class-instance) – AngYC Apr 25 '23 at 02:52

1 Answers1

0

You are not updating the x, y pos of the invader obj. You can update the constructor. Like this

constructor(x, y){
    this.x = x
    this.y = y
    this.width = 50
    this.height = 50
    const image = new Image();
    image.src = './image/invader.png'
    this.image = image
}

and loop

for(let i=0; i < invaderCount; i++){
    invaders = new Invaders(200 + i * 100, 200, i * 100); // This have diff x, y
    allInvaders.push(invaders)
}

Or simply have a func that updates x and y in the object Like

updatePos(x, y) {
    this.x = x;
    this.y = y;
}

for(let i=0; i < invaderCount; i++){
    invaders = new Invaders(); // This have diff x, y
    invaders.updatePos(200 + i * 100, 200, i * 100)
    allInvaders.push(invaders)
}