0

I have the following code in my update function, which is called 30 times per second:

        // Checking collision between rune and the players:
        for(var j = 0; j < this.players.length; j++) {
          if(this.checkCollision(this.players[j], this.runes[i])) {
            this.runes[i].activate(this.players[j]);
            this.runes[i].isHidden = true;
            this.runes[i].onDeactivate = function() {
              console.log(i);
              self.runes.splice(i, 1);
            }
          }
        }

before that I have:

for(var i = 0; i < this.runes.length; i++) ...

the self.runes.splice(i, 1) does nothing to an array... i is being set to some value. I just want to remove the not active rune from array of runes. Any Ideas?

4
  • by the way, onDeactivate is being called, i've tested that... Commented Jul 9, 2016 at 10:03
  • 1
    Out of sheer curiosity (I know exactly what's going on) but what does console.log(i) show you? Commented Jul 9, 2016 at 10:05
  • it depends on which rune I take with player... for example now it's showing 507... I wonder if self isn't a problem Commented Jul 9, 2016 at 10:06
  • You're calling self.runes.splice(i, 1) in an asynchronous function. By the time it runs, i will be outside the length of the array. Commented Jul 9, 2016 at 10:11

1 Answer 1

4

You have two problems.

Firstly, at the time of calling onDeactivate, i will have reached this.runes.length and this is what you will be seeing in the console.log(i) call. The classic fix to resolve that issue is something like:

(function(i) {
    // code that relies on i
})(i);

This will essentially "lock" the value of i for the contents of that closure.

The second problem is that splice modifies the array, and you're not accommodating for that. Let's say you have three runes:

[rune_0, rune_1, rune_2]

Now say rune_1 gets deactivated, so the code splice(1,1) is called to remove it. Now your array looks like:

[rune_0, rune_2]

Now rune_2 is deactivated, so splice(2,1) is called. That removes the [2] element from the array... but there isn't one any more.

[rune_0, rune_2]

The rune is still there.

To remove a rune from the array, you can do something like:

this.runes = this.runes.filter(function(rune) {return rune !== toremove;});

Where toremove is the rune you want gone.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.