1

I am learing gamedev using HTML 5 Canvas and while writing my second game I got strange problem. Long story short: I create particles based on enemy size when projectile and enemy collide and than I want to render those particles on the canvas. Sadly even though the number of particles being pushed to the array is correct, I'm only getting one particle rendered on the screen. Can u provide any ideas or solutions for this?

 particles.forEach((particle, idx) => {
    if (particle.alpha <= 0) particles.splice(idx, 1);
    else particle.update()
});

And the update method that is rendering particles is:

 draw() {
    c.save();
    c.globalAlpha = this._alpha;
    c.beginPath();
    c.arc(this._position.x, this._position.y, this._radius, 0, Math.PI * 2, false);
    c.fillStyle = this._color;
    c.fill();
    c.restore();
}

update() {
    this.draw();
    this._velocity.x *= friction;
    this._velocity.y *= friction;
    this._position.x += this._velocity.x;
    this._position.y += this._velocity.y;
    this._alpha -= 0.01;
}

Lastly, the code to actually push new particle to the array is:

const createParticles = (enemy: Enemy, projectile: Projectile) => {
for (let i = 0; i < enemy.radius * 2; i++) {
    particles.push(new Particle({ position: projectile.position, radius: Math.random() * 2, color: enemy.color, velocity: {
        x: (Math.random() - 0.5) * (Math.random() * 2),
        y: (Math.random() - 0.5) * (Math.random() * 2)
    }}));
}}

And the whole code can be found here: Click

I would appreciate any help, thanks :)

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Konrad
  • 153
  • 1
  • 11
  • 1
    `position: projectile.position` looks suspicious. Doesn't this mean they all alias the same position object? Maybe try `position: {...projectile.position}`. Can you share a [mcve] in the question itself? Links disappear over time. Thanks. – ggorlen Dec 29 '22 at 21:48
  • @ggorlen Well, u hit the spot perfectly, spread operator did really solve the problem. But I don't really know why there was reference conflict, cause projectile.position is the getter of my Projectile class and it should return object with new values. – Konrad Dec 29 '22 at 22:03
  • 1
    It returns the actual position object without cloning it, `return this._position;`. You might want to make that `return {...this._position};`, assuming it's only one object deep, which it appears to be for now. Or use lodash for a deep clone. – ggorlen Dec 29 '22 at 22:09

0 Answers0