You may have noticed something weird in the previous example. If you reset the game (press Ctrl+R), the gate will immediately open again as if you had triggered it. Why? This happens because memory is not reset automatically.
To ensure that things return to their initial state, you have to implement onInit to reset any memory that you use to a known initial state.
So here is our corrected code:
// onInit is called every time the game is reset: export function onInit() { card.triggered = false; } export function onTick() { if (card.triggered) { moveLeft(2); } } export function onCollision() { card.triggered = true; }
This ensures that when the game is reset, the variable triggered starts with the value of false.
There is still something weird… the gate moves infinitely to the left! Why? There is no stopping condition. Once triggered is set to true, it’s never reset.
What we want is to reset it after, say, 1 second. To do this, we can send ourselves a “delayed message” to remind ourselves to reset it:
export function onInit() { card.triggered = false; } export function onTick() { if (card.triggered) { moveLeft(2); } } export function onCollision() { card.triggered = true; // Remind ourselves to stop in 1 second. sendToSelfDelayed(1, "StopIt"); } export function onStopIt() { card.triggered = false; }
Now the gate stops after 1 second of motion.