0

I have an array with 3 elements, which were taken randomly from a larger array (let's just imagine the larger array is an alphabet, and the 3 elements array called currentChars).

I want to represent each of the character in the currentChars array with an animated sprite, which I have done through a function:

function animateChars(){
    y = 300;
    for (i=0; i<currentChars.length; i++){
        var shape = game.add.sprite(200,y,currentChars[i]);
        shape.animations.add('twinkle',null,25,true);
        shape.play('twinkle');
        y += 60;
    }
}

The player make an input, and if the input is correct, the element and its sprite should be removed from the array, and the game.

function searchAndRemove(input, arr)    {
    for(i = 0; i< arr.length; i++)  {
        if(arr[i] === input)    {
            arr.splice(i, 1);
            score += 1;
            scoreText.text = score;
            break;
        }
    }

However, I have not figured out the way to remove the sprite as the element has been taken out of the array. Ideally, the position of the other sprite should be remained when an element (and its sprite) is removed, but still, I am still stumped.

vagaryblue
  • 73
  • 1
  • 8
  • 1
    Does this help? http://stackoverflow.com/questions/24590371/destroying-sprites-in-phaser How about placing a call to `.kill` or `.destroy` before you actually remove the array element? – thelittlegumnut Aug 08 '15 at 17:41

1 Answers1

3

Phaser.Sprite objects have a destroy() method, I think that's what you're looking for. But you would have to keep a reference to the created sprite object in order to remove it later.

    myshapes[i] = game.add.sprite(200,y,currentChars[i]);

    //..

    if(arr[i] === input)    {
        myshapes[i].destroy(); // first destroy sprite
        arr.splice(i, 1); // then remove array item
        //etc.
BdR
  • 2,770
  • 2
  • 17
  • 36
  • This is the right answer. If you want to re-use the object later, I would recommend using kill() instead. – James L. Aug 29 '16 at 17:35