javascripthtmlcanvasfiddle

Space-Shooter game - bullet does't move anymore when I hit the object


I am lerning to code in javaScript and for that I am coding a space Shooter game. I came until level 2 so far but now I am having a problem which I can't fix by myself because I am not seeing the problem.

In level 2 I create some ufos which can shoot with a bullet. When the bullet gets shoot once randomly and the bullet hits the space ship the player looses a live. But when the player (so the space ship) hits the ufo it turns into a coin which the space shit can collect.

My Problem now: When the bullet of the ufo has been shot and is on his way down it stops, when the ufo gets shot by the space ship.

Why? Can someone have a look on my code?

// Move the UFO Bullet with the UFO until it's fired
if (!ufo.ufoBullet.isFired) {
  ufo.ufoBullet.x = ufo.x;
  ufo.ufoBullet.y = ufo.y;
  ufo.ufoBullet.element.style.transform = `translate(${ufo.ufoBullet.x}px, ${ufo.ufoBullet.y}px)`;
} else {
  // Move the UFO Bullet straight down when it's fired
  ufo.ufoBullet.y += ufo.ufoBullet.dy;
  ufo.ufoBullet.element.style.transform= `translate(${ufo.ufoBullet.x}px, ${ufo.ufoBullet.y}px)`;

https://jsfiddle.net/k1xesqt5/

The pictures are not in the code so the fiddle is not really working well. But the mistake must be in the function updateUFO() I guess.

Already tried not to remove the ufo object after it got hit by the space ships bullets but nothing worked. Even asked ChatGPT haha.

Here a Picture how it looks. The red bullet doesn't move after the ufo got hit. enter image description here


Solution

  • The problem is that when your UFO is shot then in line 180 (ufos.splice(i, 1);), you remove ufo variable from array ufos. Your updateUFO() function iterates over array ufos and then checks for each UFO in the array for various conditions. Also you have referenced UFO bullets by using ufo.ufoBullet, meaning that you iterate over array ufos, and then for each ufo you move its bullet by using ufo.ufoBullet. When you remove ufo from array ufos, then you can't access that ufo.ufoBullet anymore.

    That's the problem, for the solution, I would recommend that you keep a separate array ufoBullets and then iterate over ufoBullets separately, also to know which bullet belongs to which UFO you can create reference in opposite direction (Instead of ufo.ufoBullet = ufoBullet use ufoBullet.ufo = ufo). But if you want minimal change to your code, then you should add new property to ufo variable like ufo.isDestroyed which you set to true when the bullet is destroyed (in line 179) and also add property ufo.isRemovable which is set to false if bullet is fired and then is set to true when UFO bullet is destroyed. Once both ufo.isDestroyed and ufo.isRemovable than you can remove ufo from array ufos (ufos.splice(i, 1);). Also, when ufo.isDestroyed is set to true then you need to skip the part of the code for moving ufo.