Jump to content

Deleting sprites of each element in an array


sondh
 Share

Recommended Posts

I am making a simple game that could be described like this:

 

There is a large array of characters: a,b,c,d,e...

The game starts with selecting 3 random characters of the large array, and push it to an empty array, let's call it currentChars.

 

I want to represent each of the element in that currentChars array with an animated sprite, so I made this function: 

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

currentChars should return a string value in correspondence with a preloaded spritesheet, i.e. game.load.spritesheet('a', 'assets/gest/arrow.png', 32, 32);

 

If the player type any correct character in the currentChars array, that one element is deleted from the array. The relevant code, if that would matter:

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 am currently stuck at the process of deleting the sprite which the player has correctly identified. At the moment the sprite would just stack on top of each other, and I haven't figured out a method to destroy the correspondent sprite of the removed element in the currentChars array :(

 

 

Link to comment
Share on other sites

You need to store the references to the created sprites. The best way would be for each element in the currentChars array to store an Object instead of the string so you have both the character and the shape.

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

Then, in the replace function you have to destroy the sprite (shape)

function searchAndRemove(input, arr)    {    for(i = 0; i< arr.length; i++)    {        if(arr[i].char === input)    {            arr[i].shape.destroy(); // destroy the sprite            arr.splice(i, 1); // remove the entire object from the array            score += 1;            scoreText.text = score;                    break;        }    }}

Now, when you initially create the array, you would have something like this:

currentChars = [ { char: 'a', shape: null}, { char: 'x', shape: null}, { char: 'd', shape: null}, { char: 'z', shape: null}];

And the animateGestures function will replace the null shape with the actual sprite.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...