Make 2D Games with Tiniest2D
Game Loop Functions
Lesson 7 of 11 • 10 XP
Keep your place in this quest
Log in or sign up for free to subscribe, follow lesson progress, and access more learning content.
Your script can define these special functions that the engine calls automatically:
start()
Called once when the game begins. Use it for initialization.
func start() {
setScene(level1)
setX(player, 100)
setY(player, 100)
print("Game started!")
}
onUpdate(dt)
Called every frame. The dt parameter is the delta time (time since last frame in seconds).
var speed = 100
func onUpdate(dt) {
if (isKeyHeld(KEY_RIGHT())) {
setX(player, getX(player) + speed * dt)
}
if (isKeyHeld(KEY_LEFT())) {
setX(player, getX(player) - speed * dt)
}
}
UI is also drawn from onUpdate(dt). UI coordinates use a virtual screen-space resolution. By default that UI space is 100 x 100, and you can change it with setUIResolutionX() and setUIResolutionY(). Font size, font color, and element color can be pushed onto temporary per-frame stacks while you build the current UI.
var musicOn = true
var volume = 5
func onUpdate(dt) {
uiPushElementColor(28, 40, 70, 220)
uiBox(3, 3, 30, 26)
uiPushFontSize(3)
uiPushFontColor(255, 220, 120)
uiLabel("PAUSED", 6, 6)
uiPopFontColor()
uiPopFontSize()
uiPushFontSize(2)
uiPushFontColor(240, 245, 255)
if (uiButton("RESUME", 6, 12, 20, 6) == UI_CLICKED()) {
paused = false
}
musicOn = uiToggle("MUSIC", musicOn, 6, 20, 22, 6)
uiPopFontColor()
uiPopFontSize()
volume = uiSlider("VOL", volume, 0, 10, 6, 28, 24, 6)
uiPopElementColor()
}
onCollision(objA, objB)
Called when two objects collide. objA is always either a Dynamic or Trigger object (see Collision System for details).
func onCollision(objA, objB) {
var nameA = getName(objA)
var nameB = getName(objB)
if (nameA == "Player" && nameB == "Coin") {
removeObject(level1, objB)
score = score + 1
}
}
end()
Called when the game shuts down.
func end() {
print("Thanks for playing!")
}