kaplay(gopt?: KAPLAYOpt)

Initialize KAPLAY context. The starting point of all KAPLAY games.
// Start KAPLAY with default options (will create a fullscreen canvas under <body>)
kaplay()

// Init with some options
kaplay({
    width: 320,
    height: 240,
    font: "sans-serif",
    canvas: document.querySelector("#mycanvas"),
    background: [ 0, 0, 255, ],
})

// All KAPLAY functions are imported to global after calling kaplay()
add()
onUpdate()
onKeyPress()
vec2()

// If you want to prevent KAPLAY from importing all functions to global and use a context handle for all KAPLAY functions
const k = kaplay({ global: false })

k.add(...)
k.onUpdate(...)
k.onKeyPress(...)
k.vec2(...)

quit(): void

End everything.

KAPLAYOpt<TPlugin, TButtonDef>:

KAPLAY configurations.

width?: number

Width of game.

height?: number

Height of game.

scale?: number

Pixel scale / size.

stretch?: boolean

If stretch canvas to container when width and height is specified

letterbox?: boolean

When stretching if keep aspect ratio and leave black bars on remaining spaces.

debug?: boolean

If register debug buttons (default true)

debugKey?: Key

Key that toggles debug mode

font?: string

Default font (defaults to "monospace").

pixelDensity?: number

Device pixel scale (defaults to 1, high pixel density will hurt performance).

sincev3000.0

crisp?: boolean

Disable antialias and enable sharp pixel display.

canvas?: HTMLCanvasElement

The canvas DOM element to use. If empty will create one.

root?: HTMLElement

The container DOM element to insert the canvas if created. Defaults to document.body.

background?: RGBValue | RGBAValue | string

Background color. E.g. [ 0, 0, 255 ] for solid blue background, or [ 0, 0, 0, 0 ] for transparent background. Accepts RGB value array or string hex codes.

logMax?: number

How many log messages can there be on one screen (default 8).

logTime?: number

How many seconds log messages stay on screen (default 4).

sincev3000.1

hashGridSize?: number

Size of the spatial hash grid for collision detection (default 64).

sincev3000.0

touchToMouse?: boolean

If translate touch events as mouse clicks (default true).

loadingScreen?: boolean

If KAPLAY should render a default loading screen when assets are not fully ready (default true).

sincev3000.0

backgroundAudio?: boolean

If pause audio when tab is not active (default false).

sincev3000.0

gamepads?: Record<string, GamepadDef>

Custom gamepad definitions (see gamepad.json for reference of the format).

sincev3000.0

buttons?: TButtonDef

Defined buttons for input binding.

sincev30010

maxFPS?: number

Limit framerate to an amount per second.

sincev3000.0

focus?: boolean

If focus on the canvas on start (default true).

sincev3001.0

global?: boolean

If import all KAPLAY functions to global (default true).

plugins?: TPlugin

List of plugins to import.

burp?: boolean

Enter burp mode.

loadRoot(path?: string): string

Sets the root for all subsequent resource urls.
loadRoot("https://myassets.com/")
loadSprite("bean", "sprites/bean.png") // will resolve to "https://myassets.com/sprites/bean.png"

loadSprite(name: string | null, src: LoadSpriteSrc | LoadSpriteSrc[], options?: LoadSpriteOpt): Asset<SpriteData>

Load a sprite into asset manager, with name and resource url and optional config.
// due to browser policies you'll need a static file server to load local files
loadSprite("bean", "bean.png")
loadSprite("apple", "https://kaboomjs.com/sprites/apple.png")

// slice a spritesheet and add anims manually
loadSprite("bean", "bean.png", {
    sliceX: 4,
    sliceY: 1,
    anims: {
        run: {
            from: 0,
            to: 3,
        },
        jump: {
            from: 3,
            to: 3,
        },
    },
})

loadSpriteAtlas(src: LoadSpriteSrc, data: SpriteAtlasData): Asset<Record>

Load sprites from a sprite atlas.
// See #SpriteAtlasData type for format spec
loadSpriteAtlas("sprites/dungeon.png", {
    "hero": {
        x: 128,
        y: 68,
        width: 144,
        height: 28,
        sliceX: 9,
        anims: {
            idle: { from: 0, to: 3 },
            run: { from: 4, to: 7 },
            hit: 8,
        },
    },
})

const player = add([
    sprite("hero"),
])

player.play("run")

loadSpriteAtlas(src: LoadSpriteSrc, url: string): Asset<Record>

Load sprites from a sprite atlas with URL.
// Load from json file, see #SpriteAtlasData type for format spec
loadSpriteAtlas("sprites/dungeon.png", "sprites/dungeon.json")

const player = add([
    sprite("hero"),
])

player.play("run")

loadAseprite(name: string | null, imgSrc: LoadSpriteSrc, jsonSrc: string | AsepriteData): Asset<SpriteData>

Load a sprite with aseprite spritesheet json (should use "array" in the export options).
loadAseprite("car", "sprites/car.png", "sprites/car.json")

loadPedit(name: string | null, src: string): Asset<SpriteData>

loadBean(name?: string): Asset<SpriteData>

Load default sprite "bean".
loadBean()

// use it right away
add([
    sprite("bean"),
])

loadJSON(name: string | null, url: string): Asset<any>

Load custom JSON data from url.

sincev3000.0

loadSound(name: string | null, src: string | ArrayBuffer | AudioBuffer): Asset<SoundData>

Load a sound into asset manager, with name and resource url.
loadSound("shoot", "/sounds/horse.ogg")
loadSound("shoot", "/sounds/squeeze.mp3")
loadSound("shoot", "/sounds/shoot.wav")

loadMusic(name: string | null, url: string): void

Like loadSound(), but the audio is streamed and won't block loading. Use this for big audio files like background music.
loadMusic("shoot", "/music/bossfight.mp3")

loadFont(name: string, src: string | BinaryData, opt?: LoadFontOpt): Asset<FontData>

Load a font (any format supported by the browser, e.g. ttf, otf, woff).

sincev3000.0

// load a font from a .ttf file
loadFont("frogblock", "fonts/frogblock.ttf")

loadBitmapFont(name: string | null, src: string, gridWidth: number, gridHeight: number, options?: LoadBitmapFontOpt): Asset<BitmapFontData>

Load a bitmap font into asset manager, with name and resource url and information on the layout of the bitmap.

sincev3000.0

// load a bitmap font called "04b03", with bitmap "fonts/04b03.png"
// each character on bitmap has a size of (6, 8), and contains default ASCII_CHARS
loadBitmapFont("04b03", "fonts/04b03.png", 6, 8)

// load a font with custom characters
loadBitmapFont("myfont", "myfont.png", 6, 8, { chars: "☺☻♥♦♣♠" })

loadShader(name: string | null, vert?: string | null, frag?: string | null): Asset<ShaderData>

Load a shader with vertex and fragment code.
// default shaders and custom shader format
loadShader("outline",
`vec4 vert(vec2 pos, vec2 uv, vec4 color) {
    // predefined functions to get the default value by KAPLAY
    return def_vert();
}`,
`vec4 frag(vec2 pos, vec2 uv, vec4 color, sampler2D tex) {
    // turn everything blue-ish
    return def_frag() * vec4(0, 0, 1, 1);
}`, false)

loadShaderURL(name: string | null, vert?: string | null, frag?: string | null): Asset<ShaderData>

Load a shader with vertex and fragment code file url.

sincev3000.0

// load only a fragment shader from URL
loadShader("outline", null, "/shaders/outline.glsl", true)

load<T>(l: Promise): Asset<T>

Add a new loader to wait for before starting the game.
load(new Promise((resolve, reject) => {
    // anything you want to do that stalls the game in loading state
    resolve("ok")
}))

loadProgress(): number

Get the global asset loading progress (0.0 - 1.0).

sincev3000.0

getSprite(name: string): Asset | null

Get SpriteData from name.

sincev3000.0

getSound(name: string): Asset | null

Get SoundData from name.

sincev3000.0

getFont(name: string): Asset | null

Get FontData from name.

sincev3000.0

getBitmapFont(name: string): Asset | null

Get BitmapFontData from name.

sincev3000.0

getShader(name: string): Asset | null

Get ShaderData from name.

sincev3000.0

getAsset(name: string): Asset | null

Get custom data from name.

sincev3000.0

SpriteData:

width(): number

sincev3001.0

from(src: LoadSpriteSrc, opt?: LoadSpriteOpt): Promise<SpriteData>

fromImage(data: ImageSource, opt?: LoadSpriteOpt): SpriteData

fromURL(url: string, opt?: LoadSpriteOpt): Promise<SpriteData>

add<T>(comps?: CompList | GameObj): GameObj<T>

Assemble a game object from a list of components, and add it to the game

returnsThe added game object that contains all properties and methods each component offers.

const player = add([
    // List of components, each offers a set of functionalities
    sprite("mark"),
    pos(100, 200),
    area(),
    body(),
    health(8),
    // Plain strings are tags, a quicker way to let us define behaviors for a group
    "player",
    "friendly",
    // Components are just plain objects, you can pass an object literal as a component.
    {
        dir: LEFT,
        dead: false,
        speed: 240,
    },
])

// .jump is provided by body()
player.jump()

// .moveTo is provided by pos()
player.moveTo(300, 200)

// .onUpdate() is on every game object, it registers an event that runs every frame
player.onUpdate(() => {
    // .move() is provided by pos()
    player.move(player.dir.scale(player.speed))
})

// .onCollide is provided by area()
player.onCollide("tree", () => {
    destroy(player)
})

make<T>(comps?: CompList): GameObj<T>

Create a game object like add(), but not adding to the scene.

sincev3000.1

const label = make([
    text("oh hi"),
])

add([
    rect(label.width, label.height),
    color(0, 0, 255),
    children(label),
])

readd(obj: GameObj): void

Remove and re-add the game obj, without triggering add / destroy events.
// Common way to use this is to have one sprite overlap another sprite, and use readd() to have the bottom sprite on top of the other.

// Create two sprites.
const greenBean = add([
    sprite("bean"),
    pos(200,140),
    color(255, 255, 255),
    area(),
]);

// This bean will overlap the green bean.
const purpleBean = add([
    sprite("bean"),
    pos(230,140),
    color(255, 0, 255),
    area(),
]);

// Example 1: simply call readd() on the target you want on top.
readd(greenBean);

// Example 2: using onClick() or other functions with readd().
// If you comment out the first example, and use this readd() with a function like onClick(), you
can keep switching which sprite is above the other ( click on edge of face ).

purpleBean.onClick(() => {
    readd(greenBean)
});

greenBean.onClick(() => {
    readd(purpleBean)
});

get(tag: Tag | Tag[], opts?: GetOpt): GameObj[]

Get a list of all game objs with certain tag.
// get a list of all game objs with tag "bomb"
const allBombs = get("bomb")

// To get all objects use "*"
const allObjs = get("*")

// Recursively get all children and descendents
const allObjs = get("*", { recursive: true })

query(opt: QueryOpt): GameObj[]

Get a list of game objects in an advanced way.
const bean = k.add(["friend", "bean"]);
const bean2 = k.add(["friend", "bean"]);
const bag = k.add(["friend", "bag"]);

// get bean
query({
    include: "bean",
}) // will return [bean, bean2];

// get all friends excluding bean
query({
    include: "friend",
    exclude: "bean",
}); // will return [bag]

destroy(obj: GameObj): void

Remove the game obj.
// every time bean collides with anything with tag "fruit", remove it
bean.onCollide("fruit", (fruit) => {
    destroy(fruit)
})

destroyAll(tag: Tag): void

Remove all game objs with certain tag.
// destroy all objects with tag "bomb" when you click one
onClick("bomb", () => {
    destroyAll("bomb")
})

GameObjRaw:

Base interface of all game objects.

add<T>(comps?: CompList | GameObj): GameObj<T>

Add a child.

sincev3000.0

readd<T>(obj: GameObj): GameObj<T>

Remove and re-add the game obj, without triggering add / destroy events.

remove(obj: GameObj): void

Remove a child.

sincev3000.0

removeAll(tag: Tag): void

Remove all children with a certain tag.

sincev3000.0

removeAll(): void

Remove all children.

sincev3000.0

get(tag: Tag | Tag[], opts?: GetOpt): GameObj[]

Get a list of all game objs with certain tag.

sincev3000.0

query(opt: QueryOpt): GameObj[]

Get a list of all game objs with certain properties.

sincev3001.0

children: GameObj[]

Get all children game objects.

sincev3000.0

tags: string[]

Get the tags of a game object.

sincev3001.0

fixedUpdate(): void

Update this game object and all children game objects.

sincev3001.0

update(): void

Update this game object and all children game objects.

sincev3000.0

draw(): void

Draw this game object and all children game objects.

sincev3000.0

drawInspect(): void

Draw debug info in inspect mode

sincev3000.0

is(tag: Tag | Tag[]): boolean

If there's certain tag(s) on the game obj.

use(comp: Comp | Tag): void

Add a component or tag.

unuse(comp: Tag): void

Remove a tag or a component with its id.

on(event: string, action: (args: any)=>void): KEventController

Register an event.

trigger(event: string, args: any): void

Trigger an event.

destroy(): void

Remove the game obj from scene.

c(id: Tag): Comp | null

Get state for a specific comp.

inspect(): GameObjInspect

Gather debug info of all comps.

onAdd(action: ()=>void): KEventController

Register an event that runs when the game obj is added to the scene.

onUpdate(action: ()=>void): KEventController

Register an event that runs every frame as long as the game obj exists.

sincev2000.1

onDraw(action: ()=>void): KEventController

Register an event that runs every frame as long as the game obj exists (this is the same as `onUpdate()`, but all draw events are run after all update events).

sincev2000.1

onDestroy(action: ()=>void): KEventController

Register an event that runs when the game obj is destroyed.

sincev2000.1

exists(): boolean

If game obj is attached to the scene graph.

isAncestorOf(obj: GameObj): boolean

Check if is an ancestor (recursive parent) of another game object

sincev3000.0

transform: Mat4

Calculated transform matrix of a game object.

sincev3000.0

hidden: boolean

If draw the game obj (run "draw" event or not).

paused: boolean

If update the game obj (run "update" event or not).

id: GameObjID | null

A unique number ID for each game object.

canvas: FrameBuffer | null

The canvas to draw this game object on

sincev3001.0

GameObj<T>: GameObjRaw & MergeComps

The basic unit of object in KAPLAY. The player, a butterfly, a tree, or even a piece of text.

pos(x: number, y: number): PosComp

Set the position of a Game Object.
// This game object will draw a "bean" sprite at (100, 200)
add([
    pos(100, 200),
    sprite("bean"),
])

pos(xy: number): PosComp

pos(p: Vec2): PosComp

scale(x: number, y: number): ScaleComp

Set the scale of a Game Object.
// scale uniformly with one value
add([
    sprite("bean"),
	   scale(3),
])
// scale with x & y values. In this case, scales more horizontally.
add([
    sprite("bean"),
	   scale(3, 1),
])
 // scale with vec2(x,y).
bean.scale = vec2(2,4)

scale(xy: number): ScaleComp

scale(s: Vec2): ScaleComp

rotate(a?: number): RotateComp

Rotates a Game Object (in degrees).

parama The angle to rotate by. Defaults to 0.

color(r: number, g: number, b: number): ColorComp

Sets the color of a Game Object (rgb 0-255).
// blue frog
add([
    sprite("bean"),
    color(0, 0, 255)
])

color(c: Color): ColorComp

color(rgb: [number, number, number]): ColorComp

color(c: string): ColorComp

opacity(o?: number): OpacityComp

Sets the opacity of a Game Object (0.0 - 1.0).
const bean = add([
    sprite("bean"),
    opacity(0.5) // Make bean 50% transparent
])

// Make bean invisible
bean.opacity = 0

// Make bean fully visible
bean.opacity = 1

sprite(spr: string | SpriteData | Asset, options?: SpriteCompOpt): SpriteComp

Attach and render a sprite to a Game Object.
// minimal setup
add([
    sprite("bean"),
])

// with options
const bean = add([
    sprite("bean", {
        // start with animation "idle"
        anim: "idle",
    }),
])

// play / stop an anim
bean.play("jump")
bean.stop()

// manually setting a frame
bean.frame = 3

text(txt?: string, options?: TextCompOpt): TextComp

Attach and render a text to a Game Object.

paramtxt The text to display.

paramoptions Options for the text component. See

// a simple score counter
const score = add([
    text("Score: 0"),
    pos(24, 24),
    { value: 0 },
])

player.onCollide("coin", () => {
    score.value += 1
    score.text = "Score:" + score.value
})

// with options
add([
    pos(24, 24),
    text("ohhi", {
        size: 48, // 48 pixels tall
        width: 320, // it'll wrap to next line when width exceeds this value
        font: "sans-serif", // specify any font you loaded or browser built-in
    }),
])

polygon(pts: Vec2[], opt?: PolygonCompOpt): PolygonComp

Attach and render a polygon to a Game Object.

sincev3001.0

// Make a square the hard way
add([
    pos(80, 120),
    polygon([vec2(0,0), vec2(50,0), vec2(50,50), vec2(0,50)]),
    outline(4),
    area(),
])

rect(w: number, h: number, opt?: RectCompOpt): RectComp

Attach and render a rectangle to a Game Object.
const obstacle = add([
    pos(80, 120),
    rect(20, 40),
    outline(4),
    area(),
])

circle(radius: number, opt?: CircleCompOpt): CircleComp

Attach and render a circle to a Game Object.
add([
    pos(80, 120),
    circle(16),
])

uvquad(w: number, h: number): UVQuadComp

Attach and render a UV quad to a Game Object.
add([
    uvquad(width(), height()),
    shader("spiral"),
])

area(): AreaComp

Attach a collider area from shape and enables collision detection in a Game Object.
// Automatically generate area information from the shape of render
const player = add([
    sprite("bean"),
    area(),
])

// Die if player collides with another game obj with tag "tree"
player.onCollide("tree", () => {
    destroy(player)
    go("lose")
})

// Check for collision manually every frame instead of registering an event
player.onUpdate(() => {
    if (player.isColliding(bomb)) {
        score += 1
    }
})

area(options: AreaCompOpt): AreaComp

anchor(o: Anchor | Vec2): AnchorComp

Anchor point for render (default "topleft").
// set anchor to "center" so it'll rotate from center
add([
    rect(40, 10),
    rotate(45),
    anchor("center"),
])

z(z: number): ZComp

Determines the draw order for objects on the same layer. Object will be drawn on top if z value is bigger.
const bean = add([
   sprite("bean"),
   pos(100, 100),
   z(10), // Bean has a z value of 10
])

// Mark has a z value of 20, so he will always be drawn on top of bean
const mark = add([
  sprite("mark"),
  pos(100, 100),
  z(20),
])

bean.z = 30 // Bean now has a higher z value, so it will be drawn on top of mark

layer(name: string): LayerComp

Determines the layer for objects. Object will be drawn on top if the layer index is higher.
// Define layers
layers(["background", "game", "foreground"], "game")

const bean = add([
    sprite("bean"),
    pos(100, 100),
    layer("background"),
])

// Mark is in a higher layer, so he will be drawn on top of bean
const mark = add([
    sprite("mark"),
    pos(100, 100),
    layer("game"),
])

bean.layer("foreground") // Bean is now in the foreground layer and will be drawn on top of mark

outline(width?: number, color?: Color, opacity?: number, join?: LineJoin, miterLimit?: number, cap?: LineCap): OutlineComp

Give obj an outline.

particles(popt: ParticlesOpt, eopt: EmitterOpt): ParticlesComp

Attach a particle emitter to a Game Object.

parampopt The options for the particles.

parameopt The options for the emitter.

// beansplosion

// create the emitter
const emitter = add([
    pos(center()),
    particles({
        max: 100,
        speed: [75, 100],
        lifeTime: [0.75,1.0],
        angle: [0, 360],
        opacities: [1.0, 0.0],
        texture: getSprite("bean").tex,   // texture of a sprite
        quads: getSprite("bean").frames,  // frames of a sprite
    }, {
        direction: 0,
        spread: 360,
    }),
])

onUpdate(() => {
    emitter.emit(1)
})

sincev3001.0

body(options?: BodyCompOpt): BodyComp

Physical body that responds to gravity. Requires "area" and "pos" comp. This also makes the object "solid".
// bean jumpy
const bean = add([
    sprite("bean"),
    // body() requires "pos" and "area" component
    pos(),
    area(),
    body(),
])

// when bean is grounded, press space to jump
// check out #BodyComp for more methods
onKeyPress("space", () => {
    if (bean.isGrounded()) {
        bean.jump()
    }
})

// run something when bean falls and hits a ground
bean.onGround(() => {
    debug.log("oh no!")
})

surfaceEffector(options: SurfaceEffectorCompOpt): SurfaceEffectorComp

Applies a force on a colliding object in order to make it move along the collision tangent vector. Good for conveyor belts.
loadSprite("belt", "/sprites/jumpy.png")

// conveyor belt
add([
    pos(center()),
    sprite("belt"),
    rotate(90),
    area(),
    body({ isStatic: true }),
    surfaceEffector({
        speed: 50,
    })
])

sincev3001.0

areaEffector(options: AreaEffectorCompOpt): AreaEffectorComp

Applies a force on a colliding object. Good to apply anti-gravity, wind or water flow.

sincev3001.0

pointEffector(options: PointEffectorCompOpt): PointEffectorComp

Applies a force on a colliding object directed towards this object's origin. Good to apply magnetic attraction or repulsion.

sincev3001.0

buoyancyEffector(options: BuoyancyEffectorCompOpt): BuoyancyEffectorComp

Applies an upwards force (force against gravity) to colliding objects depending on the fluid density and submerged area. Good to apply constant thrust.

sincev3001.0

constantForce(opts: ConstantForceCompOpt): ConstantForceComp

Applies a constant force to the object. Good to apply constant thrust.

sincev3001.0

doubleJump(numJumps?: number): DoubleJumpComp

Enables double jump. Requires "body" component.

sincev3000.0

move(direction: number | Vec2, speed: number): EmptyComp

Move towards a direction infinitely, and destroys when it leaves game view. Requires "pos" component.
// enemy throwing feces at player
const projectile = add([
    sprite("feces"),
    pos(enemy.pos),
    area(),
    move(player.pos.angle(enemy.pos), 1200),
    offscreen({ destroy: true }),
])

offscreen(opt?: OffScreenCompOpt): OffScreenComp

Control the behavior of object when it goes out of view.

sincev2000.2

add([
    pos(player.pos),
    sprite("bullet"),
    offscreen({ destroy: true }),
    "projectile",
])

follow(obj: GameObj | null, offset?: Vec2): FollowComp

Follow another game obj's position.
const bean = add(...)

add([
  sprite("bag"),
  pos(),
  follow(bean) // Follow bean's position
])
``````js
const target = add(...)

const mark = add([
  sprite("mark"),
  pos(),
  follow(target, vec2(32, 32)) // Follow target's position with an offset
])

mark.follow.offset = vec2(64, 64) // Change the offset

shader(id: string, uniform?: Uniform | ()=>Uniform): ShaderComp

Custom shader.

textInput(hasFocus?: boolean, maxInputLength?: number): TextInputComp

Get input from the user and store it in the nodes text property, displaying it with the text component and allowing other functions to access it.
const obj = add([
    text(""),
    textInput(),
])

obj.hasFocus = false
debug.log(obj.text) // oh no i cant see my new text since it was disabled

timer(): TimerComp

Enable timer related functions like wait(), loop(), tween() on the game object.
const obj = add([
    timer(),
])

obj.wait(2, () => { ... })
obj.loop(0.5, () => { ... })
obj.tween(obj.pos, mousePos(), 0.5, (p) => obj.pos = p, easings.easeOutElastic)

fixed(): FixedComp

Make object unaffected by camera or parent object transforms, and render at last.
// this will be be fixed on top left and not affected by camera
const score = add([
    text(0),
    pos(12, 12),
    fixed(),
])

stay(scenesToStay?: string[]): StayComp

Don't get destroyed on scene switch. Only works in objects attached to root.
player.onCollide("bomb", () => {
    // spawn an explosion and switch scene, but don't destroy the explosion game obj on scene switch
    add([
        sprite("explosion", { anim: "burst", }),
        stay(),
        lifespan(1),
    ])
    go("lose", score)
})

health(hp: number, maxHP?: number): HealthComp

Handles health related logic and events.
const player = add([
    health(3),
])

player.onCollide("bad", (bad) => {
    player.hurt(1)
    bad.hurt(1)
})

player.onCollide("apple", () => {
    player.heal(1)
})

player.on("hurt", () => {
    play("ouch")
})

// triggers when hp reaches 0
player.on("death", () => {
    destroy(player)
    go("lose")
})

lifespan(time: number, options?: LifespanCompOpt): EmptyComp

Destroy the game obj after certain amount of time
// spawn an explosion, destroy after 1 seconds, start fading away after 0.5 second
add([
    sprite("explosion", { anim: "burst", }),
    lifespan(1, { fade: 0.5 }),
])

named(name: string): NamedComp

Names an object.

sincev3001.0

state(initialState: string, stateList?: string[]): StateComp

Finite state machine.

sincev2000.1

const enemy = add([
    pos(80, 100),
    sprite("robot"),
    state("idle", ["idle", "attack", "move"]),
])

// this callback will run once when enters "attack" state
enemy.onStateEnter("attack", () => {
    // enter "idle" state when the attack animation ends
    enemy.play("attackAnim", {
        // any additional arguments will be passed into the onStateEnter() callback
        onEnd: () => enemy.enterState("idle", rand(1, 3)),
    })
    checkHit(enemy, player)
})

// this will run once when enters "idle" state
enemy.onStateEnter("idle", (time) => {
    enemy.play("idleAnim")
    wait(time, () => enemy.enterState("move"))
})

// this will run every frame when current state is "move"
enemy.onStateUpdate("move", () => {
    enemy.follow(player)
    if (enemy.pos.dist(player.pos) < 16) {
        enemy.enterState("attack")
    }
})

state(initialState: string, stateList: string[], transitions: Record): StateComp

state() with pre-defined transitions.

sincev2000.2

const enemy = add([
    pos(80, 100),
    sprite("robot"),
    state("idle", ["idle", "attack", "move"], {
        "idle": "attack",
        "attack": "move",
        "move": [ "idle", "attack" ],
    }),
])

// this callback will only run once when enter "attack" state from "idle"
enemy.onStateTransition("idle", "attack", () => {
    checkHit(enemy, player)
})

fadeIn(time: number): Comp

Fade object in. Uses opacity for finding what to fade into and to set opacity during fade animation.

sincev3000.0

deprecatedsince v3001.0

mask(maskType?: Mask): MaskComp

Mask all children object render.

sincev3001.0

tile(opt?: TileCompOpt): TileComp

A tile on a tile map.

sincev3000.0

agent(opt?: AgentCompOpt): AgentComp

An agent which can finds it way on a tilemap.

sincev3000.0

animate(opt?: AnimateCompOpt): AnimateComp

A component to animate properties.

sincev3001.0

sentry(candidates: SentryCandidates, opt?: SentryCompOpt): SentryComp

A sentry which reacts to objects coming into view.

sincev3001.0

patrol(opts: PatrolCompOpt): PatrolComp

A patrol which can follow waypoints to a goal.

sincev3001.0

pathfinder(opts: PathfinderCompOpt): PathfinderComp

A navigator pathfinder which can calculate waypoints to a goal.

sincev3001.0

Comp:

id?: Tag

Component ID (if left out won't be treated as a comp).

require?: Tag[]

What other comps this comp depends on.

add?(): void

Event that runs when host game obj is added to scene.

fixedUpdate?(): void

Event that runs at a fixed frame rate.

update?(): void

Event that runs every frame.

draw?(): void

Event that runs every frame after update.

destroy?(): void

Event that runs when obj is removed from scene.

inspect?(): string | null

Debug info for inspect mode.

drawInspect?(): void

Draw debug info in inspect mode

sincev3000.0

CircleCompOpt:

Options for the circle component.

fill?: boolean

If fill the circle (useful if you only want to render outline with outline component).

OpacityComp:

The opacity component.

opacity: number

Opacity of the current object.

fadeIn(time?: number, easeFunc?: EaseFunc): TweenController

Fade in at the start.

fadeOut(time?: number, easeFunc?: EaseFunc): TweenController

Fade out at the start.

PolygonComp:

The polygon component.

sincev3001.0

pts: Vec2[]

Points in the polygon.

radius?: number | number[]

The radius of each corner.

colors?: Color[]

The color of each vertex.

uv?: Vec2[]

The uv of each vertex.

sincev3001.0

tex?: Texture

The texture used when uv coordinates are present.

sincev3001.0

PolygonCompOpt: Omit<DrawPolygonOpt, pts>

Options for the polygon component.

RectComp:

The rect component.

width: number

Width of rectangle.

height: number

Height of rectangle.

radius?: number | [number, number, number, number]

The radius of each corner.

RectCompOpt:

Options for the rect component.

radius?: number | [number, number, number, number]

Radius of the rectangle corners.

fill?: boolean

If fill the rectangle (useful if you only want to render outline with outline() component).

SpriteComp:

The sprite component.

sprite: string

Name of the sprite.

width: number

Width for sprite.

height: number

Height for sprite.

frame: number

Current frame in the entire spritesheet.

animFrame: number

Current frame in relative to the animation that is currently playing.

quad: Quad

The rectangular area of the texture to render.

play(anim: string, options?: SpriteAnimPlayOpt): void

Play a piece of anim.

stop(): void

Stop current anim.

numFrames(): number

Get total number of frames.

getCurAnim(): SpriteCurAnim | null

Get the current animation data.

sincev3001.0

curAnim(): string | undefined

Get current anim name.

deprecatedUse `getCurAnim().name` instead.

hasAnim(name: string): boolean

Check if object's sprite has an animation.

getAnim(name: string): SpriteAnim | null

Get an animation.

animSpeed: number

Speed multiplier for all animations (for the actual fps for an anim use .play("anim", { speed: 10 })).

flipX: boolean

Flip texture horizontally.

flipY: boolean

Flip texture vertically.

onAnimStart(action: (anim: string)=>void): KEventController

Register an event that runs when an animation is played.

onAnimEnd(action: (anim: string)=>void): KEventController

Register an event that runs when an animation is ended.

SpriteCompOpt:

Options for the sprite component.

frame?: number

If the sprite is loaded with multiple frames, or sliced, use the frame option to specify which frame to draw.

tiled?: boolean

If provided width and height, don't stretch but instead render tiled.

width?: number

Stretch sprite to a certain width.

height?: number

Stretch sprite to a certain height.

anim?: string

Play an animation on start.

animSpeed?: number

Speed multiplier for all animations (for the actual fps for an anim use .play("anim", { speed: 10 })).

flipX?: boolean

Flip texture horizontally.

flipY?: boolean

Flip texture vertically.

quad?: Quad

The rectangular sub-area of the texture to render, default to full texture `quad(0, 0, 1, 1)`.

fill?: boolean

If fill the sprite (useful if you only want to render outline with outline() component).

TextComp:

The text component.

text: string

The text to render.

font: string | BitmapFontData

The font to use.

width: number

Width of text.

align: TextAlign

Text alignment ("left", "center" or "right", default "left").

sincev3000.0

lineSpacing: number

The gap between each line.

sincev2000.2

textTransform: CharTransform | CharTransformFunc

Transform the pos, scale, rotation or color for each character based on the index or char.

sincev2000.1

textStyles: Record<string, CharTransform | CharTransformFunc>

Stylesheet for styled chunks, in the syntax of "this is a [style]text[/style] word".

sincev2000.2

TextCompOpt:

Options for the text component.

size?: number

Height of text.

font?: string | BitmapFontData

The font to use.

width?: number

Wrap text to a certain width.

align?: TextAlign

Text alignment ("left", "center" or "right", default "left").

sincev3000.0

lineSpacing?: number

The gap between each line.

sincev2000.2

letterSpacing?: number

The gap between each character.

sincev2000.2

transform?: CharTransform | CharTransformFunc

Transform the pos, scale, rotation or color for each character based on the index or char.

sincev2000.1

styles?: Record<string, CharTransform | CharTransformFunc>

Stylesheet for styled chunks, in the syntax of "this is a [style]text[/style] word".

sincev2000.2

FixedComp:

The fixed component.

fixed: boolean

If the obj is unaffected by camera

PosComp:

The pos component.

pos: Vec2

Object's current world position.

move(xVel: number, yVel: number): void

Move how many pixels per second. If object is 'solid', it won't move into other 'solid' objects.

move(vel: Vec2): void

moveBy(dx: number, dy: number): void

Move how many pixels, without multiplying dt, but still checking for 'solid'.

moveTo(dest: Vec2, speed?: number): void

Move to a spot with a speed (pixels per second), teleports if speed is not given.

moveTo(x: number, y: number, speed?: number): void

screenPos(): Vec2 | null

Get the position of the object on the screen.

worldPos(): Vec2 | null

Get the position of the object relative to the root.

toScreen(this: GameObj, p: Vec2): Vec2

Transform a local point (relative to this) to a screen point (relative to the camera)

toWorld(this: GameObj, p: Vec2): Vec2

Transform a local point (relative to this) to a world point (relative to the root)

sincev3001.0

fromScreen(this: GameObj, p: Vec2): Vec2

Transform a screen point (relative to the camera) to a local point (relative to this)

sincev3001.0

fromWorld(this: GameObj, p: Vec2): Vec2

Transform a world point (relative to the root) to a local point (relative to this)

sincev3001.0

toOther(this: GameObj, other: GameObj, p: Vec2): Vec2

Transform a point relative to this to a point relative to other

sincev3001.0

fromOther(this: GameObj, other: GameObj, p: Vec2): Vec2

Transform a point relative to other to a point relative to this

sincev3001.0

SentryComp:

The sentry component.

onObjectsSpotted(cb: (objects: GameObj[])=>void): KEventController

Attaches an event handler which is called when objects of interest are spotted.

paramcb The event handler called when objects are spotted.

isWithinFieldOfView(obj: GameObj, direction?: Vec2, fieldOfView?: number): boolean

Returns true if the object is within the field of view.

paramobj The object to test.

paramdirection The direction to look at.

paramfieldOfView The field of view in degrees.

hasLineOfSight(obj: GameObj): boolean

Returns true if there is a line of sight to the object.

paramobj The object to test.

TileCompOpt:

isObstacle?: boolean

If the tile is an obstacle in pathfinding.

cost?: number

How much a tile is cost to traverse in pathfinding (default 0).

edges?: Edge[]

If the tile has hard edges that cannot pass in pathfinding.

offset?: Vec2

Position offset when setting `tilePos`.

Options for the tile component.

HealthComp:

The health component.

hurt(n?: number): void

Decrease HP by n (defaults to 1).

heal(n?: number): void

Increase HP by n (defaults to 1).

hp(): number

Current health points.

setHP(hp: number): void

Set current health points.

maxHP(): number | null

Max amount of HP.

setMaxHP(hp: number): void

Set max amount of HP.

onHurt(action: (amount?: number)=>void): KEventController

Register an event that runs when hurt() is called upon the object.

sincev2000.1

onHeal(action: (amount?: number)=>void): KEventController

Register an event that runs when heal() is called upon the object.

sincev2000.1

onDeath(action: ()=>void): KEventController

Register an event that runs when object's HP is equal or below 0.

sincev2000.1

LifespanCompOpt:

The lifespan component.

fade?: number

Fade out duration (default 0 which is no fade out).

StateComp:

The state component.

state: string

Current state.

enterState(state: string, args: any): void

Enter a state, trigger onStateEnd for previous state and onStateEnter for the new State state.

onStateTransition(from: string, to: string, action: ()=>void): KEventController

Register event that runs once when a specific state transition happens. Accepts arguments passed from `enterState(name, ...args)`.

sincev2000.2

onStateEnter(state: string, action: (args: any)=>void): KEventController

Register event that runs once when enters a specific state. Accepts arguments passed from `enterState(name, ...args)`.

onStateEnd(state: string, action: ()=>void): KEventController

Register an event that runs once when leaves a specific state.

onStateUpdate(state: string, action: ()=>void): KEventController

Register an event that runs every frame when in a specific state.

onStateDraw(state: string, action: ()=>void): KEventController

Register an event that runs every frame when in a specific state.

StayComp:

The stay component.

stay: boolean

If the obj should not be destroyed on scene switch.

scenesToStay?: string[]

Array of scenes that the obj will stay on.

TextInputComp:

The stay component.

hasFocus: boolean

Enable the text input array from being modified by user input.

TimerComp:

The timer component.

wait(time: number, action?: ()=>void): TimerController

Run the callback after n seconds.

loop(time: number, action: ()=>void): KEventController

Run the callback every n seconds.

sincev3000.0

tween<V>(from: V, to: V, duration: number, setValue: (value: V)=>void, easeFunc?: (t: number)=>number): TweenController

Tweeeeen! Note that this doesn't specifically mean tweening on this object's property, this just registers the timer on this object, so the tween will cancel with the object gets destroyed, or paused when obj.paused is true.

sincev3000.0

AreaComp:

The area component.

area:

shape: Shape | null

If we use a custom shape over render shape.

cursor: Cursor | null

Cursor on hover.

Collider area info.

collisionIgnore: Tag[]

If this object should ignore collisions against certain other objects.

sincev3000.0

isClicked(): boolean

If was just clicked on last frame.

checkCollision(other: GameObj): Collision | null

Check collision with another game obj.

sincev3000.0

getCollisions(): Collision[]

Get all collisions currently happening.

sincev3000.0

isColliding(o: GameObj): boolean

If is currently colliding with another game obj.

isOverlapping(o: GameObj): boolean

If is currently overlapping with another game obj (like isColliding, but will return false if the objects are just touching edges).

onClick(f: ()=>void, btn?: MouseButton): void

Register an event runs when clicked.

sincev2000.1

onHover(action: ()=>void): KEventController

Register an event runs once when hovered.

sincev3000.0

onHoverUpdate(action: ()=>void): KEventController

Register an event runs every frame when hovered.

sincev3000.0

onHoverEnd(action: ()=>void): KEventController

Register an event runs once when unhovered.

sincev3000.0

onCollide(tag: Tag, f: (obj: GameObj, col?: Collision)=>void): void

Register an event runs once when collide with another game obj with certain tag.

sincev2001.0

onCollide(f: (obj: GameObj, col?: Collision)=>void): void

Register an event runs once when collide with another game obj.

sincev2000.1

onCollideUpdate(tag: Tag, f: (obj: GameObj, col?: Collision)=>void): KEventController

Register an event runs every frame when collide with another game obj with certain tag.

sincev3000.0

onCollideUpdate(f: (obj: GameObj, col?: Collision)=>void): KEventController

Register an event runs every frame when collide with another game obj.

sincev3000.0

onCollideEnd(tag: Tag, f: (obj: GameObj)=>void): KEventController

Register an event runs once when stopped colliding with another game obj with certain tag.

sincev3000.0

onCollideEnd(f: (obj: GameObj)=>void): void

Register an event runs once when stopped colliding with another game obj.

sincev3000.0

hasPoint(p: Vec2): boolean

If has a certain point inside collider.

resolveCollision(obj: GameObj): void

Push out from another solid game obj if currently overlapping.

localArea(): Shape

Get the geometry data for the collider in local coordinate space.

sincev3000.0

worldArea(): Polygon

Get the geometry data for the collider in world coordinate space.

screenArea(): Polygon

Get the geometry data for the collider in screen coordinate space.

AreaCompOpt:

Options for the area component.

shape?: Shape

The shape of the area (currently only Rect and Polygon is supported).
add([
    sprite("butterfly"),
    pos(100, 200),
    // a triangle shape!
    area({ shape: new Polygon([vec2(0), vec2(100), vec2(-100, 100)]) }),
])

scale?: number | Vec2

Area scale.

cursor?: Cursor

Cursor on hover.

collisionIgnore?: Tag[]

If this object should ignore collisions against certain other objects.

sincev3000.0

BodyComp:

The body component.

vel: Vec2

Object current velocity.

sincev3001.0

drag: number

How much velocity decays (velocity *= (1 - drag) every frame).

sincev3001.0

isStatic: boolean

If object is static, won't move, and all non static objects won't move past it.

jumpForce: number

Initial speed in pixels per second for jump().

mass: number

Mass of the body, decides how much a non-static body should move when resolves with another non-static body. (default 1).

sincev3000.0

stickToPlatform?: boolean

If object should move with moving platform (default true).

sincev3000.0

curPlatform(): GameObj | null

Current platform landing on.

isGrounded(): boolean

If currently landing on a platform.

sincev2000.1

isFalling(): boolean

If currently falling.

sincev2000.1

isJumping(): boolean

If currently rising.

sincev3000.0

applyImpulse(impulse: Vec2): void

Applies an impulse

paramimpulse The impulse vector, applied directly

addForce(force: Vec2): void

Applies a force

paramforce The force vector, applied after scaled by the inverse mass

jump(force?: number): void

Upward thrust.

onPhysicsResolve(action: (col: Collision)=>void): KEventController

Register an event that runs when a collision is resolved.

sincev3000.0

onBeforePhysicsResolve(action: (col: Collision)=>void): KEventController

Register an event that runs before a collision would be resolved.

sincev3000.0

onGround(action: ()=>void): KEventController

Register an event that runs when the object is grounded.

sincev2000.1

onFall(action: ()=>void): KEventController

Register an event that runs when the object starts falling.

sincev2000.1

onFallOff(action: ()=>void): KEventController

Register an event that runs when the object falls off platform.

sincev3000.0

onHeadbutt(action: ()=>void): KEventController

Register an event that runs when the object bumps into something on the head.

sincev2000.1

onLand(action: (obj: GameObj)=>void): KEventController

Register an event that runs when an object lands on this object.

sincev3001.0

onHeadbutted(action: (obj: GameObj)=>void): KEventController

Register an event that runs when the object is bumped by another object head.

BodyCompOpt:

Options for the body component.

drag?: number

How much velocity decays (velocity *= (1 - drag) every frame).

sincev3001.0

jumpForce?: number

Initial speed in pixels per second for jump().

isStatic?: boolean

If object is static, won't move, and all non static objects won't move past it.

sincev3000.0

stickToPlatform?: boolean

If object should move with moving platform (default true).

sincev3000.0

mass?: number

Mass of the body, decides how much a non-static body should move when resolves with another non-static body. (default 1).

sincev3000.0

DoubleJumpComp:

The doubleJump component.

numJumps: number

Number of jumps allowed.

doubleJump(force?: number): void

Performs double jump (the initial jump only happens if player is grounded).

onDoubleJump(action: ()=>void): KEventController

Register an event that runs when the object performs the second jump when double jumping.

AnchorComp:

The anchor component.

anchor: Anchor | Vec2

Anchor point for render.

LayerComp:

The layer component.

layerIndex(): number | null

Get the index of the current layer the object is assigned to.

returnsThe index of the layer the object is assigned to, or `null` if the layer does not exist.

layer(): string | null

Get the name of the current layer the object is assigned to.

returnsThe name of the layer the object is assigned to.

layer(name: string):

Set the name of the layer the object should be assigned to.

OffScreenComp:

The offscreen component.

isOffScreen(): boolean

If object is currently out of view.

onExitScreen(action: ()=>void): KEventController

Register an event that runs when object goes out of view.

onEnterScreen(action: ()=>void): KEventController

Register an event that runs when object enters view.

OffScreenCompOpt:

Options for offscreen component.

hide?: boolean

If hide object when out of view.

pause?: boolean

If pause object when out of view.

destroy?: boolean

If destroy object when out of view.

distance?: number

The distance when out of view is triggered (default 200).

sincev3000.0

RotateComp:

The rotate component.

angle: number

Angle in degrees.

rotateBy(angle: number): void

Rotate in degrees.

rotateTo(s: number): void

Rotate to a degree (like directly assign to .angle)

sincev3000.0

ScaleComp:

The scale component.

scale: Vec2

The current scale of the object

returnsThe current scale of the object as a

scaleTo(s: number): void

Set the scale of the object to a number

scaleTo(s: Vec2): void

Set the scale of the object to a Vec2

scaleTo(sx: number, sy: number): void

Set the scale of the object to a number for x and y

scaleBy(s: number): void

Scale the object by a number

scaleBy(s: Vec2): void

Scale the object by a Vec2

scaleBy(sx: number, sy: number): void

Scale the object by a number for x and y

ZComp:

The z component.

z: number

Defines the z-index of this game obj

MergeComps<T>: Omit<MergeObj, Bug parsing TypeOperator>

A type to merge the components of a game object, omitting the default component properties.

CompList<T>: Array<T | Tag>

A component list.

EmptyComp:

id: string

&
Comp

A component without own properties.

LevelComp:

A level component.

spawn(sym: string, p: Vec2): GameObj | null

Spawn a tile from a symbol defined previously.

spawn(sym: string, x: number, y: number): GameObj | null

spawn<T>(obj: CompList, p: Vec2): GameObj | null

Spawn a tile from a component list.

returnsThe spawned game object, or null if the obj hasn't components.

spawn<T>(sym: CompList, x: number, y: number): GameObj | null

levelWidth(): number

Total width of level in pixels.

getAt(tilePos: Vec2): GameObj[]

Get all game objects that's currently inside a given tile.

raycast(origin: Vec2, direction: Vec2): RaycastResult

Raycast all game objects on the given path.

tile2Pos(tilePos: Vec2): Vec2

Convert tile position to pixel position.

pos2Tile(pos: Vec2): Vec2

Convert pixel position to tile position.

getTilePath(from: Vec2, to: Vec2, opts?: PathFindOpt): Vec2[] | null

Find the path to navigate from one tile to another tile.

returnsA list of traverse points in tile positions.

getPath(from: Vec2, to: Vec2, opts?: PathFindOpt): Vec2[] | null

Find the path to navigate from one tile to another tile.

returnsA list of traverse points in pixel positions.

getSceneName(): string | null

Gets the name of the current scene. Returns null if no scene is active.

sincev3001.0

scene(id: SceneName, def: SceneDef): void

Define a scene.

go(id: SceneName, args: any): void

Go to a scene, passing all rest args to scene callback.

layers(layers: string[], defaultLayer: string): void

Define the layer names. Should be called before any objects are made.

onGamepadConnect(action: (gamepad: KGamepad)=>void): void

Register an event that runs when a gamepad is connected.

sincev3000.0

onGamepadDisconnect(action: (gamepad: KGamepad)=>void): void

Register an event that runs when a gamepad is disconnected.

sincev3000.0

onClick(tag: Tag, action: (a: GameObj)=>void): KEventController

Register an event that runs when game objs with certain tags are clicked (required to have the area() component).

sincev2000.1

// click on any "chest" to open
onClick("chest", (chest) => chest.open())

onClick(action: ()=>void): KEventController

Register an event that runs when users clicks.
// click on anywhere to go to "game" scene
onClick(() => go("game"))

sincev2000.1

onKeyDown(key: Key | Key[], action: (key: Key)=>void): KEventController

Register an event that runs every frame when a key is held down.
// move left by SPEED pixels per frame every frame when left arrow key is being held down
onKeyDown("left", () => {
    bean.move(-SPEED, 0)
})

sincev2000.1