Z
Z
zlodiak2018-09-22 23:18:11
JavaScript
zlodiak, 2018-09-22 23:18:11

Why are the missiles not removed?

I wrote a simple game script. Two players exchange fire with missiles. If the rocket hits the player, then the player's energy decreases.
JSFIDDLE
The problem is that after the missile misses the player and flies off the screen, it inexplicably continues to exist.
This is expressed in the fact that if the player moves his ship over time to the place of the rocket that has flown away, then he receives a decrease in energy
. screen and went beyond the screen (here my script using splice removes the rocket from the array of rockets) 4. you can see that the energy of the right player has not changed
5. the right player also takes 4 steps up
6. as a result, the energy of the right player has decreased (although there is no rocket at this place)
Please help me fix the script.
Control keys: q, a, z, w, s, x

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Svyatoslav, 2018-09-22
@zlodiak

It is necessary to add the condition of their destruction to the condition for the movement of missiles
. For example, like this

if (rocket.type === "left") {
  if (rocket.xCoord < parseInt(this.fieldEl.style.width)) {
    rocket.move();
  } else if (rocket.xCoord === parseInt(this.fieldEl.style.width)) {
    this.rockets.splice(index, 1);
    return;
  }
}

if (rocket.type === "right") {
  if (rocket.xCoord > 0) {
    rocket.move();
  } else if (rocket.xCoord === 0) {
    this.rockets.splice(index, 1);
    return;
  }
}

0
0xD34F, 2018-09-22
@0xD34F

the rocket flew the entire length of the screen and went beyond the screen (here my script using splice removes the rocket from the array of rockets)

Doesn't delete. You don't have any code that does that. There is a code responsible for moving - with a check for reaching the screen border, and there is no else branch, in which the deletion should take place. There is a removal of the rocket in a collision with a ship. There is no deletion when going beyond the screen boundaries. He is not here. NO.
And splice inside forEach is not a sin to cut off your hands for.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question