Skip to main content

Timing

You'll often want to wait for a bit before running more code. This section will show you a few ways of doing this.

castle.runAfterDelay()

castle.runAfterDelay lets you schedule a function to run after a certain amount of time. In this example, we want to run the function moveDown() 0.5 seconds after the box is tapped.

Try tapping on the box. You can also tap on the box a few times in a row to see what happens.

This deck contains the default "Wall" blueprint with a script added.

You can also do this without defining a separate function:

This deck contains the default "Wall" blueprint with a script added.

Or use a local variable to store the function:

This deck contains the default "Wall" blueprint with a script added.

castle.repeatAtInterval()

This function is similar to castle.runAfterDelay, but it keeps running the function until you stop it.

Here's an example where we run rotate() every 0.5 seconds:

This deck contains the default "Wall" blueprint with a script added.

If you want to stop repeating the function you, can use castle.stopRepeat. Here's an example where tapping the box will stop it from rotating:

This deck contains the default "Wall" blueprint with a script added.

Manually with onUpdate()

In some cases, keeping track of the total time yourself might be easier. This example behaves the same as the last example, but we manually keep track of the time in onUpdate.

This deck contains the default "Wall" blueprint with a script added.

Here's an example of using more complex logic in onUpdate. We could use castle.repeatAtInterval to replicate this logic, but it would probably be a lot more complicated.

This deck contains the default "Wall" blueprint with a script added.

castle.sleep()

warning

We recommend not using this. It will prevent the rest of your script (including onUpdate and onMessage) from running until it returns. You can almost always perform the same logic with a combination of the previous techniques.

If you really just want to pause the code for a bit, you can use castle.sleep. As stated above, this will pause your entire script.

In this example, we call castle.sleep when the box is tapped. This partially works but has a couple of bugs:

  • Since castle.sleep pauses the entire script, it also stops onUpdate from being called for 1 second. When onUpdate is eventually called, dt is set to 1 second, since that's the amount of time that has passed since the previous onUpdate, which causes the box to jump instead of continuing to rotate smoothly.
  • If you tap the box multiple times, the sleeps will stack up and it will take a long time to start rotating again.
This deck contains the default "Wall" blueprint with a script added.

Here's an example using castle.runAfterDelay instead. This example does require a few more lines of code, but it doesn't have the same bugs as the previous example.

This deck contains the default "Wall" blueprint with a script added.