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 specifiedletterbox?: 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 modefont?: string
Default font (defaults to "monospace").pixelDensity?: number
Device pixel scale (defaults to 1, high pixel density will hurt performance).since
v3000.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.texFilter?: TexFilter
Default texture filter.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).since
v3000.1
hashGridSize?: number
Size of the spatial hash grid for collision detection (default 64).since
v3000.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).since
v3000.0
backgroundAudio?: boolean
If pause audio when tab is not active (default false).since
v3000.0
gamepads?: Record<string, GamepadDef>
Custom gamepad definitions (see gamepad.json for reference of the format).since
v3000.0
buttons?: TButtonDef
Defined buttons for input binding.since
v30010
maxFPS?: number
Limit framerate to an amount per second.since
v3000.0
focus?: boolean
If focus on the canvas on start (default true).since
v3001.0
global?: boolean
If import all KAPLAY functions to global (default true).plugins?: TPlugin
List of plugins to import.burp?: boolean
Enter burp mode.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(...)
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.since
v3000.0
loadSound(name: string | null, src: string | ArrayBuffer): 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).since
v3000.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 infomation on the layout of the bitmap.since
v3000.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, frag?: string): 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, frag?: string): Asset<ShaderData>
Load a shader with vertex and fragment code file url.since
v3000.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).since
v3000.0
getSprite(name: string): Asset | null
Get SpriteData from name.since
v3000.0
getSound(name: string): Asset | null
Get SoundData from name.since
v3000.0
getFont(name: string): Asset | null
Get FontData from name.since
v3000.0
getBitmapFont(name: string): Asset | null
Get BitmapFontData from name.since
v3000.0
getShader(name: string): Asset | null
Get ShaderData from name.since
v3000.0
getAsset(name: string): Asset | null
Get custom data from name.since
v3000.0
Asset<D>:
An asset is a resource that is loaded asynchronously.loaded: boolean
loaded<D>(data: D): Asset<D>
data: D | null
error: Error | null
onLoadEvents:
onErrorEvents:
onFinishEvents:
onLoad(action: (data: D)=>void): Bug parsing ThisType
onError(action: (err: Error)=>void): Bug parsing ThisType
onFinish(action: ()=>void): Bug parsing ThisType
then(action: (data: D)=>void): Asset<D>
catch(action: (err: Error)=>void): Asset<D>
finally(action: ()=>void): Asset<D>
SpriteData:
tex: Texture
frames: Quad[]
anims: SpriteAnims
slice9: NineSlice | null
width(): number
since
v3001.0
height(): number
from(src: LoadSpriteSrc, opt?: LoadSpriteOpt): Promise<SpriteData>
fromImage(data: ImageSource, opt?: LoadSpriteOpt): SpriteData
fromURL(url: string, opt?: LoadSpriteOpt): Promise<SpriteData>
SoundData:
buf: AudioBuffer
fromArrayBuffer(buf: ArrayBuffer): Promise<SoundData>
fromURL(url: string): Promise<SoundData>
add<T>(comps?: CompList | GameObj): GameObj<Bug parsing ConditionalType>
Assemble a game object from a list of components, and add it to the gamereturns
The 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<Bug parsing ConditionalType>
Create a game object like add(), but not adding to the scene.since
v3000.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<Bug parsing ConditionalType>
Add a child.since
v3000.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.since
v3000.0
removeAll(tag: Tag): void
Remove all children with a certain tag.since
v3000.0
removeAll(): void
Remove all children.since
v3000.0
get(tag: Tag | Tag[], opts?: GetOpt): GameObj[]
Get a list of all game objs with certain tag.since
v3000.0
query(opt: QueryOpt): GameObj[]
Get a list of all game objs with certain properties.since
v3001.0
children: GameObj[]
Get all children game objects.since
v3000.0
tags: string[]
Get the tags of a game object.since
v3001.0
fixedUpdate(): void
Update this game object and all children game objects.since
v3001.0
update(): void
Update this game object and all children game objects.since
v3000.0
draw(): void
Draw this game object and all children game objects.since
v3000.0
drawInspect(): void
Draw debug info in inspect modesince
v3000.0
clearEvents(): void
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.since
v2000.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).since
v2000.1
onDestroy(action: ()=>void): KEventController
Register an event that runs when the game obj is destroyed.since
v2000.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 objectsince
v3000.0
transform: Mat4
Calculated transform matrix of a game object.since
v3000.0
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 onsince
v3001.0
onKeyDown: KAPLAYCtx[onKeyDown]
onKeyPress: KAPLAYCtx[onKeyPress]
onKeyPressRepeat: KAPLAYCtx[onKeyPressRepeat]
onKeyRelease: KAPLAYCtx[onKeyRelease]
onCharInput: KAPLAYCtx[onCharInput]
onMouseDown: KAPLAYCtx[onMouseDown]
onMousePress: KAPLAYCtx[onMousePress]
onMouseRelease: KAPLAYCtx[onMouseRelease]
onMouseMove: KAPLAYCtx[onMouseMove]
onTouchStart: KAPLAYCtx[onTouchStart]
onTouchMove: KAPLAYCtx[onTouchMove]
onTouchEnd: KAPLAYCtx[onTouchEnd]
onScroll: KAPLAYCtx[onScroll]
onGamepadButtonDown: KAPLAYCtx[onGamepadButtonDown]
onGamepadButtonPress: KAPLAYCtx[onGamepadButtonPress]
onGamepadButtonRelease: KAPLAYCtx[onGamepadButtonRelease]
onGamepadStick: KAPLAYCtx[onGamepadStick]
onButtonDown: KAPLAYCtx[onButtonDown]
onButtonPress: KAPLAYCtx[onButtonPress]
onButtonRelease: KAPLAYCtx[onButtonRelease]
GameObj<T>: GameObjRaw & MergeComps
The basic unit of object in KAPLAY. The player, a butterfly, a tree, or even a piece of text.GameObjID: number
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
pos(): 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
scale(): ScaleComp
rotate(a: number): RotateComp
Rotates a Game Object (in degrees).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
color(): ColorComp
opacity(o?: number): OpacityComp
Sets the opacity of a Game Object (0.0 - 1.0).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.// 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.since
v3001.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): 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.layer(name: string): LayerComp
Determines the layer for objects. Object will be drawn on top if the layer index is higher.outline(width?: number, color?: Color): OutlineComp
Give obj an outline.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.since
v3001.0
areaEffector(options: AreaEffectorCompOpt): AreaEffectorComp
Applies a force on a colliding object. Good to apply anti-gravity, wind or water flow.since
v3001.0
pointEffector(options: PointEffectorCompOpt): PointEffectorComp
Applies a force on a colliding object directed towards this object's origin. Good to apply magnetic attractiong or repulsion.since
v3001.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.since
v3001.0
constantForce(opts: ConstantForceCompOpt): ConstantForceComp
Applies a constant force to the object. Good to apply constant thrust.since
v3001.0
doubleJump(numJumps?: number): DoubleJumpComp
Enables double jump. Requires "body" component.since
v3000.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.since
v2000.2
add([ pos(player.pos), sprite("bullet"), offscreen({ destroy: true }), "projectile", ])
follow(obj: GameObj | null, offset?: Vec2): FollowComp
Follow another game obj's position.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.since
v3001.0
state(initialState: string, stateList?: string[]): StateComp
Finite state machine.since
v2000.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.since
v2000.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.since
v3000.0
deprecated
since v3001.0
mask(maskType?: Mask): MaskComp
Mask all children object render.since
v3001.0
tile(opt: TileCompOpt): TileComp
A tile on a tile map.since
v3000.0
agent(opt?: AgentCompOpt): AgentComp
An agent which can finds it way on a tilemap.since
v3000.0
animate(): AnimateComp
A component to animate properties.since
v3001.0
sentry(candidates: SentryCandidates, opt?: SentryCompOpt): SentryComp
A sentry which reacts to objects coming into view.since
v3001.0
patrol(opts: PatrolCompOpt): PatrolComp
A patrol which can follow waypoints to a goal.since
v3001.0
navigation(opts: NavigationCompOpt): NavigationComp
A navigator which can calculate waypoints to a goal.since
v3001.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 modesince
v3000.0
CircleComp:
The circle component.
draw: Comp[draw]
radius: number
Radius of circle.renderArea(): Rect
Render area of the circle.since
v3000.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.OutlineComp:
The outline component.
outline: Outline
PolygonComp:
The polygon component.
since
v3001.0
draw: Comp[draw]
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.since
v3001.0
tex?: Texture
The texture used when uv coordinates are present.since
v3001.0
renderArea(): Polygon
PolygonCompOpt: Omit<DrawPolygonOpt, pts>
Options for the polygon component.
RectComp:
The rect component.
draw: Comp[draw]
width: number
Width of rectangle.height: number
Height of rectangle.radius?: number
The radius of each corner.renderArea(): Rect
since
v3000.0
RectCompOpt:
Options for the rect component.
radius?: number
Radius of the rectangle corners.fill?: boolean
If fill the rectangle (useful if you only want to render outline with outline() component).ShaderComp:
The shader component.
uniform?: Uniform
shader: string
SpriteComp:
The sprite component.
draw: Comp[draw]
sprite: string
Name of the sprite.width: number
Width for sprite.height: number
Height for sprite.frame: number
Current frame.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.since
v3001.0
curAnim(): string | undefined
Get current anim name.deprecated
Use `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.renderArea(): Rect
since
v3000.0
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.
draw: Comp[draw]
text: string
The text to render.renderedText: string
The text after formatting.textSize: number
The text size.font: string | BitmapFontData
The font to use.width: number
Width of text.height: number
Height of text.align: TextAlign
Text alignment ("left", "center" or "right", default "left").since
v3000.0
lineSpacing: number
The gap between each line.since
v2000.2
letterSpacing: number
The gap between each character.since
v2000.2
textTransform: CharTransform | CharTransformFunc
Transform the pos, scale, rotation or color for each character based on the index or char.since
v2000.1
textStyles: Record<string, CharTransform | CharTransformFunc>
Stylesheet for styled chunks, in the syntax of "this is a [style]text[/style] word".since
v2000.2
renderArea(): Rect
since
v3000.0
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").since
v3000.0
lineSpacing?: number
The gap between each line.since
v2000.2
letterSpacing?: number
The gap between each character.since
v2000.2
transform?: CharTransform | CharTransformFunc
Transform the pos, scale, rotation or color for each character based on the index or char.since
v2000.1
styles?: Record<string, CharTransform | CharTransformFunc>
Stylesheet for styled chunks, in the syntax of "this is a [style]text[/style] word".since
v2000.2
UVQuadComp:
The uvquad component.
draw: Comp[draw]
width: number
Width of rect.height: number
Height of height.renderArea(): Rect
since
v3000.0
AgentComp:
The agent component.
agentSpeed: number
allowDiagonals: boolean
getDistanceToTarget(): number
getNextLocation(): Vec2 | null
getPath(): Vec2[] | null
getTarget(): Vec2 | null
isNavigationFinished(): boolean
isTargetReachable(): boolean
isTargetReached(): boolean
setTarget(target: Vec2): void
onNavigationStarted(cb: ()=>void): KEventController
onNavigationNext(cb: ()=>void): KEventController
onNavigationEnded(cb: ()=>void): KEventController
onTargetReached(cb: ()=>void): KEventController
AgentCompOpt: speed?: number
allowDiagonals?: boolean
speed?: number
allowDiagonals?: boolean
Options for the agent component.
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'.moveBy(d: Vec2): void
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)since
v3001.0
fromScreen(this: GameObj, p: Vec2): Vec2
Transform a screen point (relative to the camera) to a local point (relative to this)since
v3001.0
fromWorld(this: GameObj, p: Vec2): Vec2
Transform a world point (relative to the root) to a local point (relative to this)since
v3001.0
toOther(this: GameObj, other: GameObj, p: Vec2): Vec2
Transform a point relative to this to a point relative to othersince
v3001.0
fromOther(this: GameObj, other: GameObj, p: Vec2): Vec2
Transform a point relative to other to a point relative to thissince
v3001.0
SentryComp:
The sentry component.
direction?: Vec2
directionAngle?: number
fieldOfView?: number
spotted: GameObj[]
onObjectsSpotted(cb: (objects: GameObj[])=>void): KEventController
Attaches an event handler which is called when objects of interest are spotted.param
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.param
The object to test.
hasLineOfSight(obj: GameObj): boolean
Returns true if there is a line of sight to the object.param
The object to test.
SentryCompOpt:
Options for the sentry component.
direction?: Vec2 | number
fieldOfView?: number
lineOfSight?: boolean
raycastExclude?: string[]
checkFrequency?: number
TileComp:
The tile component.
tilePos: Vec2
The tile position inside the level.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.tilePosOffset: Vec2
Position offset when setting `tilePos`.edgeMask: EdgeMask
getLevel(): GameObj<LevelComp>
moveLeft(): void
moveRight(): void
moveUp(): void
moveDown(): void
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`.
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.since
v2000.1
onHeal(action: (amount?: number)=>void): KEventController
Register an event that runs when heal() is called upon the object.since
v2000.1
onDeath(action: ()=>void): KEventController
Register an event that runs when object's HP is equal or below 0.since
v2000.1
LifespanCompOpt:
The lifespan component.
fade?: number
Fade out duration (default 0 which is no fade out).NamedComp:
The named component.
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)`.since
v2000.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.since
v3000.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.since
v3000.0
AreaComp:
The area component.
area: shape: Shape | null
If we use a custom shape over render shape.scale: Vec2
Area scale.offset: Vec2
Area offset.cursor: Cursor | null
Cursor on hover.
Collider area info.shape: Shape | null
If we use a custom shape over render shape.scale: Vec2
Area scale.offset: Vec2
Area offset.cursor: Cursor | null
Cursor on hover.collisionIgnore: Tag[]
If this object should ignore collisions against certain other objects.since
v3000.0
isClicked(): boolean
If was just clicked on last frame.isHovering(): boolean
If is being hovered on.checkCollision(other: GameObj): Collision | null
Check collision with another game obj.since
v3000.0
getCollisions(): Collision[]
Get all collisions currently happening.since
v3000.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.since
v2000.1
onHover(action: ()=>void): KEventController
Register an event runs once when hovered.since
v3000.0
onHoverUpdate(action: ()=>void): KEventController
Register an event runs every frame when hovered.since
v3000.0
onHoverEnd(action: ()=>void): KEventController
Register an event runs once when unhovered.since
v3000.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.since
v2001.0
onCollide(f: (obj: GameObj, col?: Collision)=>void): void
Register an event runs once when collide with another game obj.since
v2000.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.since
v3000.0
onCollideUpdate(f: (obj: GameObj, col?: Collision)=>void): KEventController
Register an event runs every frame when collide with another game obj.since
v3000.0
onCollideEnd(tag: Tag, f: (obj: GameObj)=>void): KEventController
Register an event runs once when stopped colliding with another game obj with certain tag.since
v3000.0
onCollideEnd(f: (obj: GameObj)=>void): void
Register an event runs once when stopped colliding with another game obj.since
v3000.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.since
v3000.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.offset?: Vec2
Area offset.cursor?: Cursor
Cursor on hover.collisionIgnore?: Tag[]
If this object should ignore collisions against certain other objects.since
v3000.0
BodyComp:
The body component.
vel: Vec2
Object current velocity.since
v3001.0
drag: number
How much velocity decays (velocity *= (1 - drag) every frame).since
v3001.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().gravityScale: number
Gravity multiplier.mass: number
Mass of the body, decides how much a non-static body should move when resolves with another non-static body. (default 1).since
v3000.0
stickToPlatform?: boolean
If object should move with moving platform (default true).since
v3000.0
curPlatform(): GameObj | null
Current platform landing on.isGrounded(): boolean
If currently landing on a platform.since
v2000.1
isFalling(): boolean
If currently falling.since
v2000.1
isJumping(): boolean
If currently rising.since
v3000.0
applyImpulse(impulse: Vec2): void
Applies an impulseparam
The impulse vector, applied directly
addForce(force: Vec2): void
Applies a forceparam
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.since
v3000.0
onBeforePhysicsResolve(action: (col: Collision)=>void): KEventController
Register an event that runs before a collision would be resolved.since
v3000.0
onGround(action: ()=>void): KEventController
Register an event that runs when the object is grounded.since
v2000.1
onFall(action: ()=>void): KEventController
Register an event that runs when the object starts falling.since
v2000.1
onFallOff(action: ()=>void): KEventController
Register an event that runs when the object falls off platform.since
v3000.0
onHeadbutt(action: ()=>void): KEventController
Register an event that runs when the object bumps into something on the head.since
v2000.1
onLand(action: (obj: GameObj)=>void): KEventController
Register an event that runs when an object lands on this object.since
v3001.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).since
v3001.0
jumpForce?: number
Initial speed in pixels per second for jump().maxVelocity?: number
Maximum velocity when falling.gravityScale?: number
Gravity multiplier.isStatic?: boolean
If object is static, won't move, and all non static objects won't move past it.since
v3000.0
stickToPlatform?: boolean
If object should move with moving platform (default true).since
v3000.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).since
v3000.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.FollowComp:
The follow component.
follow: obj: GameObj
offset: Vec2
obj: GameObj
offset: Vec2
LayerComp:
The layer component.
layerIndex(): number | null
Get the index of the current layer the object is assigned to.returns
The 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.returns
The 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).since
v3000.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)since
v3000.0
ScaleComp:
The scale component.
scale: Vec2
The current scale of the objectreturns
scaleTo(s: number): void
Set the scale of the object to a numberscaleTo(s: Vec2): void
Set the scale of the object to a Vec2scaleTo(sx: number, sy: number): void
Set the scale of the object to a number for x and yscaleBy(s: number): void
Scale the object by a numberscaleBy(s: Vec2): void
Scale the object by a Vec2scaleBy(sx: number, sy: number): void
Scale the object by a number for x and yMergeComps<T>: Omit<MergeObj, Bug parsing TypeOperator>
A type to merge the components of a game object, omiting the default component properties.CompList<T>: Array<T | Tag>
A component list.LevelComp:
A level component.tileWidth(): number
tileHeight(): number
numRows(): number
numColumns(): number
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.returns
The 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.levelHeight(): number
Total height 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.tile2Pos(x: number, y: number): Vec2
pos2Tile(pos: Vec2): Vec2
Convert pixel position to tile position.pos2Tile(x: number, y: number): Vec2
getTilePath(from: Vec2, to: Vec2, opts?: PathFindOpt): Vec2[] | null
Find the path to navigate from one tile to another tile.returns
A 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.returns
A list of traverse points in pixel positions.
getSpatialMap(): GameObj[][]
onSpatialMapChanged(cb: ()=>void): KEventController
onNavigationMapInvalid(cb: ()=>void): KEventController
invalidateNavigationMap(): void
onNavigationMapChanged(cb: ()=>void): KEventController
getSceneName(): string | null
Gets the name of the current scene. Returns null if no scene is active.since
v3001.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(layernames: 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.since
v3000.0
onGamepadDisconnect(action: (gamepad: KGamepad)=>void): void
Register an event that runs when a gamepad is disconnected.since
v3000.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).since
v2000.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"))
since
v2000.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) })
since
v2000.1
onKeyDown(action: (key: Key)=>void): KEventController
Register an event that runs every frame when any key is held down.since
v2000.1
onKeyPress(key: Key | Key[], action: (key: Key)=>void): KEventController
Register an event that runs when user presses certain keys.// .jump() once when "space" is just being pressed onKeyPress("space", () => { bean.jump() }); onKeyPress(["up", "space"], () => { bean.jump() });
since
v2000.1
onKeyPress(action: (key: Key)=>void): KEventController
Register an event that runs when user presses any key.// Call restart() when player presses any key onKeyPress((key) => { debug.log(`key pressed ${key}`) restart() })
since
v3001.0
onKeyPressRepeat(k: Key | Key[], action: (k: Key)=>void): KEventController
Register an event that runs when user presses certain kesy (also fires repeatedly when the keys are being held down).// delete last character when "backspace" is being pressed and held onKeyPressRepeat("backspace", () => { input.text = input.text.substring(0, input.text.length - 1) })
since
v3000.1