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 removeufovariable from arrayufos. YourupdateUFO()function iterates over arrayufosand 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 eachufoyou move its bullet by usingufo.ufoBullet. When you removeufofrom arrayufos, then you can't access thatufo.ufoBulletanymore.That's the problem, for the solution, I would recommend that you keep a separate array
ufoBulletsand then iterate overufoBulletsseparately, also to know which bullet belongs to which UFO you can create reference in opposite direction (Instead ofufo.ufoBullet = ufoBulletuseufoBullet.ufo = ufo). But if you want minimal change to your code, then you should add new property toufovariable likeufo.isDestroyedwhich you set totruewhen the bullet is destroyed (in line 179) and also add propertyufo.isRemovablewhich is set tofalseif bullet is fired and then is set totruewhen UFO bullet is destroyed. Once bothufo.isDestroyedandufo.isRemovablethan you can removeufofrom arrayufos(ufos.splice(i, 1);). Also, whenufo.isDestroyedis set totruethen you need to skip the part of the code for movingufo.