Events

An Event is something that happens in the game, for example, the player pressing a key, clicking the mouse or an enemy being hurt.

An Event Handler is a method that listens for events and run code when they happen. These functions are named as on{EventName}.

// onKeyPress() will run every time user press any key
onKeyPress((key) => {
    // Some events send you args related to them, in this case the key pressed
    debug.log(key); // will log the key pressed
});

Event Handlers also return an Event Controller. It works for cancel the event or pause it:

const pressEvent = onKeyPress((key) => {
    debug.log(key);
});

pressEvent.cancel(); // stop running the handler

There’s many type of events that runs in different contexts:

App events

App events run without neccesity of being attached to a game object. They are related to things like the game screen, input, etc.

// Only runs when user press "a"
onKeyPress("a", () => {
    debug.log("aaa");
});

// Only runs when assets finish loading
onLoad(() => {});

Root events

Root events run during the lifecycle of the Root Game Object, or the same, forever.

// onUpdate() event runs every frame.
onUpdate(() => {
    // Bean moves 10px to the right every frame
    bean.moveBy(10, 0);
});

// onDraw() event runs after update and must be used with drawXXXX functions.
onDraw(() => {
    // The sprite is drawn here to prevent it from disappearing after 1 frame.
    drawSprite("bean");
});

You can also associate these event handlers with Tags, this means you can run an event handler code 4 times if there’s 4 objects with that tag. The first argument is always the game object is running for.

// imagine there's 4 objects with tag "friend"

// onUpdate("friend") will be executed 4 times per frame (or the same, 1 time per object)
onUpdate("friend", (o) => {
    // o will take 4 different values
    debug.log(o.id);
});

Game Object events

Game Object events are like Root events, but they operate on individual Game Objects. These events run during specific points in the object’s lifecycle, such as when it’s added, updated, or removed.

const obj = add([]);

// Runs when the object is added
obj.onAdd(() => {});
// Runs when the object is destroyed
obj.onDestroy(() => {});

// They run while obj exists
obj.onUpdate(() => {});
obj.onDraw(() => {});

Both Object and Root events operate with Object Events List

Game Object events given by components

There are events and events handlers that comes from some components. They become events of the object after add the comp:

const kat = add([
    // health(initialHp) comp gives to the object a health system
    health(4),
]);

// Given by health(), runs when we hurt the obj
kat.onHurt(() => {
    debug.log("you're a monster!");
});

// Run when user clicks
onMousePress(() => {
    kat.hurt(1); // we remove 1 hp, ouch
});

Generic handler

on() is a way to create handlers without they being premade. In fact, all events handler are an on().

You can use global on(), it works for use Game Object events with certain tags. The first argument is always the object. It is useful when there’s no a handler for tags, for example in the component events:

// obj.onHurt() but for many objects
on("hurt", "friend", (o) => {
    debug.log(o.id);
});

on("update", "friend", (o) => {
    debug.log(o.id + "exists");
});

There’s also the object version, obj.on(). Useful for listen to an event only in that obj:

kat.on("hurt", () => {
});

Custom events

Sometimes you will need create a custom event. For this, we use the on() and obj.trigger() functions.

// Eat event for all objects with cake tag
on("eat", "cake", () => {
    debug.log("The cake is a lie!");
});

onKeyPress(() => {
    obj.trigger("eat");
});

Events operations

How to listen for an event

// a global event
onUpdate(() => {});
// an object event
obj.onUpdate(() => {});
// a custom event
obj.on("hi", () => {});

How to trigger an event

// will execute obj.on("hi", () => {})
obj.trigger("hi"); // :>

List of events

  • 🏷️ = Require tags for working

Object Events List

EventCompDescriptionGlobal HandlerObject Handler
updateNoneRuns every frameonUpdate()obj.onUpdate()
drawNoneRuns every frame after updateonDraw()obj.onDraw()
addNoneRuns when an object is added as childonAdd()obj.onAdd()
destroyNoneRuns when an object is destroyedonDestroy()obj.onDestroy()
useNoneRuns when a component is addedonUse()obj.onUse(comp)
unuseNoneRuns when a component is unusedonUnuse()obj.onUnuse(comp)
tagNoneRuns when a tag is addedonTag()obj.onTag(tag)
untagNoneRuns when a tag is removedonUntag()obj.onUntag(tag)
collidearea()Runs when object collides with another objectonCollide() 🏷️obj.onCollide(other, col)
collideUpdatearea()Runs every frame when objects are collidingonCollideUpdate() 🏷️obj.onCollideUpdate()
collideEndarea()Runs when object stops collidingonCollideEnd() 🏷️obj.onCollideEnd()
hurthealth()Runs when object is hurtUsing on()obj.onHurt(damage)
healhealth()Runs when object is healedUsing on()obj.onHeal(amount)
deathhealth()Runs when object diesUsing on()obj.onDeath()
beforePhysicsResolvebody()Runs before physics resolvesUsing on()obj.onBeforePhysics(col)
physicsResolvebody()Runs after physics resolvesUsing on()obj.onPhysics(col)
groundbody()Runs when object is on the groundUsing on()obj.onGround()
fallbody()Runs when object starts fallingUsing on()obj.onFall()
fallOffbody()Runs when object stops fallingUsing on()obj.onFallOff()
headbuttbody()Runs when object headbuttsUsing on()obj.onHeadbutt()
landbody()Runs when object landsUsing on()obj.onLand()
headbuttedbody()Runs when object is headbuttedUsing on()obj.onHeadbutted()
doubleJumpdoubleJumpRuns when object double jumpsUsing on()obj.onDoubleJump()
exitViewoffscreen()Runs when object goes out of viewUsing on()obj.onExitView()
enterViewoffscreen()Runs when object enters viewUsing on()obj.onEnterView()
animStartsprite()Runs when animation startsUsing on()obj.onAnimStart(anim)
animEndsprite()Runs when animation endsUsing on()obj.onAnimEnd(anim)
navigationNextagent()Runs when navigation moves to the next pointUsing on()obj.onNavigationNext()
navigationEndedagent()Runs when navigation endsUsing on()obj.onNavigationEnded()
navigationStartedagent()Runs when navigation startsUsing on()obj.onNavigationStarted()
targetReachedagent()Runs when navigation target is reachedUsing on()obj.onTargetReached()
patrolFinishedpatrol()Runs when patrol finishesUsing on()obj.onPatrolFinished()
objectSpottedsentry()Runs when object spots anotherUsing on()obj.onObjectSpotted()
animateChannelFinishedanimate()Runs when animation channel finishesUsing on()obj.onAnimateChannel()
animateFinishedanimateRuns when animation finishesUsing on()obj.onAnimateFinished()
spatialMapChangedlevel()Runs when spatial map changesUsing on()obj.onSpatialMapChanged()
navigationMapInvalidlevel()Runs when navigation map becomes invalidUsing on()obj.onNavigationMapInvalid()
avigationMapChangedlevel()Runs when navigation map changesUsing on()obj.onNavigationMapChanged()

App Events List

EventDescriptionGlobal HandlerObject Handler
mouseMoveRuns continuously while mouse movesonMouseMove()obj.onMouseMove()
mouseDownRuns continuously while mouse is clickedonMouseDown()obj.onMouseDown()
mousePressRuns once when mouse button is pressedonMousePress()obj.onMousePress()
mouseReleaseRuns once when mouse button is releasedonMouseRelease()obj.onMouseRelease()
charInputRuns continuously while user write in the keyboardonCharInput()obj.onCharInput()
keyPressRuns once when a key is pressedonKeyPress()obj.onKeyPress()
keyDownRuns continuously while a key is held downonKeyDown()obj.onKeyDown()
keyPressRepeatRuns once when a key is repeatedly pressedonKeyPressRepeat()obj.onKeyPressRepeat()
keyReleaseRuns once when a key is releasedonKeyRelease()obj.onKeyRelease()
touchStartRuns once when a touch startsonTouchStart()obj.onTouchStart()
touchMoveRuns continously while a touch movesonTouchMove()obj.onTouchMove()
touchEndRuns once when a touch endsonTouchEnd()obj.onTouchEnd()
gamepadButtonDownRuns continously while a gamepad button is held downonGamepadButtonDown()obj.onGamepadButtonDown()
gamepadButtonPressRuns once when a gamepad button is pressedonGamepadButtonPress()obj.onGamepadButtonPress()
gamepadButtonReleaseRuns once when a gamepad button is releasedonGamepadButtonRelease()obj.onGamepadButtonRelease()
gamepadStickRuns continuously while a gamepad stick movesonGamepadStick()obj.onGamepadStick()
gamepadConnectRuns once when a gamepad connectsonGamepadConnect()obj.onGamepadConnect()
gamepadDisconnectRuns once when a gamepad disconnectsonGamepadDisconnect()obj.onGamepadDisconnect()
buttonDownRuns continuously while an input binding is held downonButtonDown()obj.onButtonDown()
buttonPressRuns once when an input binding is pressedonButtonPress()obj.onButtonPress()
buttonReleaseRuns once when a binding button is releasedonButtonRelease()obj.onButtonRelease()
scrollRuns continuously while a scroll event occursonScroll()obj.onScroll()
hideRuns once when the game tab is hiddenonHide()No ❌
showRuns once when the game tab is showedonShow()No ❌
resizeRuns continously when the game screen is resizingonResize()No ❌
inputRuns when the input is processedNo ❌No ❌
kaplay logo

Making Your First Game

Expanding KAPLAY