0

Hi I am playing around with building a small game in JS, and I am getting an unforeseen error when animating 2 objects.

I have a class for sprites defined as such:

class Sprite {
constructor({position, image_src}){
    this.position = position;
    this.image = new Image();
    this.image.src = image_src;
}

draw(){
    c.drawImage( 
        this.image, 
        this.position.x - this.image.width / 2, 
        this.position.y - this.image.height / 2
       );
}

}

I create two new instances like this:

   const center = {x: canvas.width/2, y: canvas.heigth/2} 

const background = new Sprite({
    position: center,
    image_src: './Assets/Images/UV.png', 
})

    const player = new Sprite({
        position: center,
        image_src: './Assets/Images/playerDown.png',
    })

and I animate its position with wasd as such

function animate(){
window.requestAnimationFrame(animate);
background.draw(); 
player.draw();

if(keys.up.pressed){ background.position.y += 3)}
else if... 

What i want to happen is the background moving, and NOT the player. What actually happens (and in my mind shouldn't) is that both background and player get moved. I tried some debugging, and I noticed that my const object "center" changes, and thus with it any Sprite that uses it in its constructor.

I can easily work around it, by using two different objects in the constructor, but it bug my mind WHY does it work like that, and HOW should I make it work.

Can anyone help?

  • 1
    Both of your sprites refer to the **same** `center` object via `this.position`, so changing the properties of that object affects both sprites ([more here](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language)). You need to copy the object. Just `this.position = { ...position };` will do it in this case. – T.J. Crowder Oct 04 '22 at 17:03

0 Answers0