I have a class that represents a sprite of an explosion.
I want this sprite to play only once and then be freed from memory.
Currently I'm defining a variable my_explosion
that instantiates the class Explosion
Then inside draw I draw the current Sprite frame, I increase the frame index, and then I check if the index is greater than the number of images. If that's the case I assign the variable
my_explosion
to undefined
.
class Explosion{
constructor(images) {
this.index = 0;
this.images = images;
}
show() {
// show the current frame and increase the frame index
image(this.images[this.index], 0, 0);
this.index += 1;
}
}
let my_explosion = undefined;
setup() {
// images is a preloaded array of images
my_explosion = new Explosion(images);
}
draw() {
// check if my_explosion is defined
if (my_explosion) {
my_explosion.show();
// this is the check that I'd rather like to
// be done by the class itself
if (my_explosion.index >= my_explosion.images.length) {
my_explosion = undefined;
}
}
}
Now, I have a couple of questions.
- Currently I have to check if I reached the last image outside the class. Ideally I would like that the class itself checks when it has to be destroyed and destroys itself. I'm not sure if this is possible, since the variable holding the class instance is defined outside the class itself.
Is there a way of doing this check and destruction that keeps the code more encapsulated?
- Is setting the instance variable to
undefined
the correct way of destroying the class? Will the instance be garbage collected and effectively freed from memory?