Projectile Despawning

Hi, I’m making a game where if you press A, a function is called that makes a new projectile under the variable ‘playerprojectile’ is created. I tried to make a timer that deletes a projectile after 2000ms but it only deletes the most recent projectile created. So if you spammed A, a few projectiles will stay and a few will instantly delete, can anyone help me?


This is what i put in the function

@h3ythat there is actually built in support for destroying a sprite after some number of milliseconds.

In the “set sprite property” block (the same one with x, y, etc.), there is a field called lifetime. If you set that to a number of milliseconds, the sprite will automatically get destroyed after that amount of time has passed.

…but to more generally explain what is going on here, you have to understand that all variables in blocks are global. as you observed, if you reassign the global playerprojectile variable by running this code multiple times, the variable will only ever point to whichever projectile was created most recently.

there is a trick to work around this shortcoming by using function parameters. parameters passed into functions are not global and will not be reassigned if you call the function multiple times, so you can do stuff like run some code in an “after ___ do” block without running into any problems.

i know that’s confusing, so let’s look at an example. say I wanted to create a function that spawns a projectile and then makes it turn after a second.

here’s a bad implementation of that function:

image

this will have the same bug you’re seeing because it’s using a global variable.

we can fix this by moving the asynchronous part of the code into it’s own function:

image

the two parameters we pass into that function, sprite and millis, won’t change even if the function is called again.

here’s a project with those two functions:

2 Likes

Thank you for showing me the ways, dapper pigeon.

1 Like