1

I've pretty much gotten past this problem by attacking to from a different angle, but I would like to know why my first approach didn't work.

In my game I had and array:

let inventory = [null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null];

And to help manage it I made two methods.

The first one would put string into the array:

collect(item) {
    this.space = 0;
    while (this.space < 18){
        if (inventory[this.space] == null){
            inventory[this.space] == item;
            break;
        }
        else {
            this.space += 1;
        }
    }
}

And the second one checks if a string is even in the array:

has(item){
    this.space = 0;
    this.result = false
    while (this.space < inventory.length){
        if (inventory[this.space] == item){
            this.result = true;
            break;
        }
        else {
            this.space += 1;
        }
    }
    return this.result;
}

The has method works just fine, but for some reason, the collect method never worked. Despite using a similar system of loops and if statements, the method always left the array full of nulls.

Since the array called inventory was a global variable, I chalked it up to that as an explanation and switched to using the push function. But recently I tried using this approach again with an array that was local to its scene, but I got the same result: the string never went into the array.

I may be comfortable using the push function again, but I still wish to know: why did the collect method never work in the first place? Is there something in Phaser that prevents one from setting a specific slot in an array in this manner?

If it helps anyone, I'm using Phaser 3 in VSCode employing arcade physics.

winner_joiner
  • 12,173
  • 4
  • 36
  • 61
EmptyStone
  • 235
  • 1
  • 7

1 Answers1

0

You can and should use builtin functions in , this would also prevent errors.
(the problem in the collect function is the typo == while setting the value, in the line inventory[this.space] == item;)

In any case, with built in function's collect could look like this:

collect(item) {
    let firstEmptyIndex = inventory.indexOf(null)
    if(firstEmptyIndex > -1){
        inventory[firstEmptyIndex] = item;
    }
}

And has would look like this:

has(item) {
    return inventory.indexOf(item) > -1;
}

For more information to the function indexOf. Link to documentation

winner_joiner
  • 12,173
  • 4
  • 36
  • 61