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.
The problem is that when your UFO is shot then in line 180 (
ufos.splice(i, 1);
), you removeufo
variable from arrayufos
. YourupdateUFO()
function iterates over arrayufos
and then checks for each UFO in the array for various conditions. Also you have referenced UFO bullets by usingufo.ufoBullet
, meaning that you iterate over arrayufos
, and then for eachufo
you move its bullet by usingufo.ufoBullet
. When you removeufo
from arrayufos
, then you can't access thatufo.ufoBullet
anymore.That's the problem, for the solution, I would recommend that you keep a separate array
ufoBullets
and then iterate overufoBullets
separately, also to know which bullet belongs to which UFO you can create reference in opposite direction (Instead ofufo.ufoBullet = ufoBullet
useufoBullet.ufo = ufo
). But if you want minimal change to your code, then you should add new property toufo
variable likeufo.isDestroyed
which you set totrue
when the bullet is destroyed (in line 179) and also add propertyufo.isRemovable
which is set tofalse
if bullet is fired and then is set totrue
when UFO bullet is destroyed. Once bothufo.isDestroyed
andufo.isRemovable
than you can removeufo
from arrayufos
(ufos.splice(i, 1);
). Also, whenufo.isDestroyed
is set totrue
then you need to skip the part of the code for movingufo
.