Farhan Ganayim
Farhan Ganayim

Reputation: 9

Sometimes in Space Invaders JS I shoot two aliens when the shoot hits the same time aliens shift

I would be very grateful for any help, trying to code Space Invaders in JS, managed to move aliens in functions to shift the board right left and down in Intervals, the laser shoot is also in another Interval moving it up. The problem that sometimes when the laser hits the exact time aliens are shifting it shoots two aliens, and my alien counter on the screen doesn't match the actual seen on the game, and cant finish the game, i finish the game according to the global var aliens counter, is it a problem of Intervals, or handleHit function I am not sure.

https://github.com/Farhan-Ganayim/Space-Invaders https://farhan-ganayim.github.io/Space-Invaders/

I managed to shoot aliens and the score is fine, that happens when play game with slow aliens and shoot them accurately, but when setting the interval to 1 sec, sometimes the problem of shooting two aliens happens.

function handleAlienHit(pos) {
    
    // clearInterval(laserInterval)
    // updateCell(pos,null)
    gGame.alienCount--    
    updateScore()
    gHero.isShoot=false  
}

function blinkLaser(pos) {
    // var cellGameObject=gBoard[pos.i][pos.j].gameObject
    updateCell(pos, LASER)
    setTimeout(() => {
        updateCell(pos, null)
    }, 80)
}

Upvotes: 0

Views: 78

Answers (1)

Wyck
Wyck

Reputation: 11770

You are passing a position object by reference as if it had value semantics.

function blinkLaser(pos) {

    updateCell(pos, LASER)
    setTimeout(() => {
        updateCell(pos, null)  // <-- Oops! The properties of pos may have changed!
    }, 80)
}

pos is an object that you defined in your shoot function (it's called laserPos in that code). You reuse this same object in all cases where a position is used, but you modify its properties by calling laserPos.i--.

That means that it's possible that the properties of pos can be changed after you call updateCell(pos, LASER) but before the timeout elapses. Then, since updateCell(pos, null) is referring to the one-and-only position object, but its properties have changed, your blinkLaser function isn't updating the screen properly.

Copy the position

You could fix this by writing updateCell({ ...pos }, null) to make a shallow copy of the position object so that you null out the same position that you updated earlier in the function at updateCell(pos, LASER).

Upvotes: 1

Related Questions