If you want to repeatedly do something in your game, you can add a callback method to game.onUpdateInterval
like game.onUpdateInterval(500, () => doSomething())
. But you cannot unsubscribe this callback from being executed - never.
If you want to do something periodically but only for a certain time, the pxt-interval extension can help you: https://github.com/ractive/pxt-interval/
It’s a typescript-only extension and cannot be used in block mode.
A callback handler that is registered to be executed in a given interval can also be unsubscribed again. The call to Interval.on
returns a function that can be called to do the unsubscription:
const unsubscribe = Interval.on(500, () => doSomething());
...
unsubscribe();
Here’s an example how to fire projectiles every 500 milliseconds for 3 seconds:
const unsubscribe = Interval.on(500, () => sprites.createProjectileFromSprite(myImage, mySprite, 50, 0));
setTimeout(() => unsubscribe(), 3000);
Another example that lets a spaceship shoot until it’s getting destroyed:
const spaceShip = sprites.create(someSpaceshipImage);
spaceShip.setFlag(SpriteFlag.AutoDestroy, true);
const unsubscribe = Interval.on(500, () => {
sprites.createProjectileFromSprite(img`
1
1
`, spaceShip, 0, -80);
});
spaceShip.vx = 30;
spaceShip.onDestroyed(() => unsubscribe());
Using it in your project
To use this extension in your javascript project, choose “Advanced > Extensions…” and enter https://github.com/ractive/pxt-interval
in the search box.
This extension uses the pxt-heap extension to easily fetch the next callback handler that should be executed.