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(...)
group
Start
End everything.
since
v2000.0
group
Start
KAPLAYOpt<TPlugin, TButtonDef>:
KAPLAY configurations.
group
Start
Width of game.
Height of game.
Pixel scale / size.
If stretch canvas to container when width and height is specified
When stretching if keep aspect ratio and leave black bars on remaining spaces.
If register debug buttons (default true)
Key that toggles debug mode
font?: string
Default font (defaults to "monospace").
Device pixel scale (defaults to 1, high pixel density will hurt performance).
since
v3000.0
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.
Default texture filter.
How many log messages can there be on one screen (default 8).
How many seconds log messages stay on screen (default 4).
since
v3000.1
Size of the spatial hash grid for collision detection (default 64).
since
v3000.0
If translate touch events as mouse clicks (default true).
If KAPLAY should render a default loading screen when assets are not fully ready (default true).
since
v3000.0
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
Defined buttons for input binding.
since
v30010
Limit framerate to an amount per second.
since
v3000.0
If focus on the canvas on start (default true).
since
v3001.0
If import all KAPLAY functions to global (default true).
List of plugins to import.
burp?: boolean
Enter burp mode.
Make component's id ("sprite" for sprite() comp) be added as tags.
That means .is() will return true for components with that id.
default
true
experimental
This feature is in experimental phase, it will be fully released in v4000.0
Padding used when adding sprites to texture atlas.
default
0
experimental
This feature is in experimental phase, it will be fully released in v4000.0
loadRoot(path?: string): string
Sets the root for all subsequent resource urls.
This is useful when you want to load assets from a different domain, or setup
a base path for all assets.
param
path- The root path.
loadRoot("https://myassets.com/");
loadSprite("bean", "sprites/bean.png"); // will resolve to "https://myassets.com/sprites/bean.png"
loadRoot("./"); // useful for Itch.io
group
Assets
loadSprite(name: string | null, src: LoadSpriteSrc | LoadSpriteSrc[], opt?: LoadSpriteOpt): Asset<SpriteData>
Load a sprite into asset manager, with name and resource url and optional config.
param
name- The asset name.
param
src- The resource url.
param
opt- The optional config.
// due to browser policies you'll need a static file server to load local files
loadSprite("bean", "bean.png");
loadSprite("apple", "https://play.kaplayjs.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,
},
},
});
returns
The asset data.
since
v2000.0
group
Assets
loadSpriteAtlas(src: LoadSpriteSrc, data: SpriteAtlasData): Asset<Record>
Load sprites from a sprite atlas.
param
src- The image resource url.
param
data- The sprite atlas data.
// 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");
returns
The asset data.
since
v2000.0
group
Assets
loadSpriteAtlas(src: LoadSpriteSrc, url: string): Asset<Record>
Load sprites from a sprite atlas with URL.
param
src- The image resource url.
param
url- The json resource 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")
returns
The asset data.
since
v2000.0
group
Assets
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).
param
name- The asset name.
param
imgSrc- The image resource url.
loadAseprite("car", "sprites/car.png", "sprites/car.json")
returns
The asset data.
since
v2000.0
group
Assets
loadPedit(name: string | null, src: string): Asset<SpriteData>
param
name- The asset name.
param
src- The resource url.
Load .pedit file.
deprecated
The format is not supported anymore.
returns
The asset data.
since
v2000.0
group
Assets
loadBean(name?: string): Asset<SpriteData>
Load default sprite "bean".
param
name- The optional name for bean.
loadBean();
// use it right away
add([
sprite("bean"),
]);
returns
The asset data.
since
v2000.0
group
Assets
loadJSON(name: string | null, url: string): Asset<any>
Load custom JSON data from url.
param
name- The asset name.
param
url- The resource url.
returns
The asset data.
since
v3000.0
group
Assets
loadSound(name: string | null, src: string | ArrayBuffer | AudioBuffer): Asset<SoundData>
Load a sound into asset manager, with name and resource url.
Supported formats: mp3, ogg, wav.
param
name- The asset name.
param
src- The resource url.
loadSound("shoot", "/sounds/horse.ogg");
loadSound("shoot", "/sounds/squeeze.mp3");
loadSound("shoot", "/sounds/shoot.wav");
returns
The asset data.
since
v2000.0
group
Assets
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.
param
name- The asset name.
param
url- The resource url.
loadMusic("shoot", "/music/bossfight.mp3");
returns
The asset data.
since
v3001.0
group
Assets
loadFont(name: string, src: string | BinaryData, opt?: LoadFontOpt): Asset<FontData>
Load a font (any format supported by the browser, e.g. ttf, otf, woff).
param
name- The asset name.
// load a font from a .ttf file
loadFont("frogblock", "fonts/frogblock.ttf");
returns
The asset data.
since
v3000.0
group
Assets
loadBitmapFont(name: string | null, src: string, gridW: number, gridH: number, opt?: LoadBitmapFontOpt): Asset<BitmapFontData>
Load a bitmap font into asset manager, with name and resource url and information on the layout of the bitmap.
param
name- The asset name.
param
src- The resource url.
param
gridW- The width of each character on the bitmap.
param
gridH- The height of each character on the bitmap.
param
opt- The options for the bitmap font.
// 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: "☺☻♥♦♣♠" });
returns
The asset data.
since
v3000.0
group
Assets
loadShader(name: string | null, vert?: string | null, frag?: string | null): Asset<ShaderData>
Load a shader with vertex and fragment code.
param
name- The asset name.
param
vert- The vertex shader code. Null if not needed.
param
frag- The fragment shader code. Null if not needed.
// 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)
returns
The asset data.
since
v2000.0
group
Assets
loadShaderURL(name: string | null, vert?: string | null, frag?: string | null): Asset<ShaderData>
Load a shader with vertex and fragment code file url.
param
name- The name of the asset.
param
vert- The vertex shader code. Null if not needed.
param
frag- The fragment shader code. Null if not needed.
// load only a fragment shader from URL
loadShaderURL("outline", null, "/shaders/outline.glsl")
retunrs
The asset data.
since
v3000.0
group
Assets
load<T>(l: Promise): Asset<T>
Add a new loader to wait for before starting the game.
param
l- The loader to wait for.
load(new Promise((resolve, reject) => {
// anything you want to do that stalls the game in loading state
resolve("ok")
}))
returns
The asset data.
since
v3000.0
group
Assets
Get the global asset loading progress (0.0 - 1.0).
returns
The loading progress.
since
v3000.0
group
Assets
getSprite(name: string): Asset | null
Get SpriteData from name.
param
name- The asset name.
returns
The asset data.
since
v3000.0
group
Assets
getSound(name: string): Asset | null
Get SoundData from name.
param
name- The asset name.
returns
The asset data.
since
v3000.0
group
Assets
getFont(name: string): Asset | null
Get FontData from name.
param
name- The asset name.
returns
The asset data.
since
v3000.0
group
Assets
getBitmapFont(name: string): Asset | null
Get BitmapFontData from name.
param
name- The asset name.
returns
The asset data.
since
v3000.0
group
Assets
getShader(name: string): Asset | null
Get ShaderData from name.
param
name- The asset name.
returns
The asset data.
since
v3000.0
group
Assets
getAsset(name: string): Asset | null
Get custom data from name.
param
name- The asset name.
returns
The asset data.
since
v3000.0
group
Assets
An asset is a resource that is loaded asynchronously.
loaded<D>(data: D): Asset<D>
data: D | null
error: Error | null
onLoad(action: (data: D)=>void): this
onError(action: (err: Error)=>void): this
onFinish(action: ()=>void): this
then(action: (data: D)=>void): Asset<D>
catch(action: (err: Error)=>void): Asset<D>
finally(action: ()=>void): Asset<D>
tex: Texture
anims: SpriteAnims
slice9: NineSlice | null
since
v3001.0
from(src: LoadSpriteSrc, opt?: LoadSpriteOpt): Promise<SpriteData>
fromImage(data: ImageSource, opt?: LoadSpriteOpt): SpriteData
fromURL(url: string, opt?: LoadSpriteOpt): Promise<SpriteData>
buf: AudioBuffer
fromArrayBuffer(buf: ArrayBuffer): Promise<SoundData>
fromURL(url: string): Promise<SoundData>
add<T>(comps?: CompList | GameObj): GameObj<T>
Assemble a game object from a list of components, and add it to the game,
param
comps- List of components to add to the game object, or a game object made with
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);
});
returns
The added game object that contains all properties and methods each component offers.
group
Game Obj
make<T>(comps?: CompList): GameObj<T>
Create a game object like add(), but not adding to the scene.
param
comps- List of components to add to the game object.
const label = make([
rect(100, 20),
]);
// Add a new text to the label
label.add([
text("Hello, world!"),
]);
// Add game object to the scene
// Now it will render
add(label);
returns
The created game object that contains all properties and methods each component offers.
since
v3000.1
group
Game Obj
readd(obj: GameObj): GameObj
Remove and re-add the game obj, without triggering add / destroy events.
param
obj- The game object to re-add.
// 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);
});
returns
The re-added game object.
since
v3001.0
group
Game Obj
get(tag: Tag | Tag[], opts?: GetOpt): GameObj[]
Get a list of all game objs with certain tag.
param
tag- The tag to search for. Use "*" to get all objects.
param
opts- Additional options.
// 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 });
returns
A list of game objects that have the tag.
since
v2000.0
group
Game Obj
query(opt: QueryOpt): GameObj[]
Get a list of game objects in an advanced way.
param
opt- The query options.
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]
group
Game Obj
destroy(obj: GameObj): void
Remove the game obj.
param
obj- The game object to remove.
// every time bean collides with anything with tag "fruit", remove it
bean.onCollide("fruit", (fruit) => {
destroy(fruit);
});
group
Game Obj
Remove all game objs with certain tag.
param
tag- The tag to search for.
// destroy all objects with tag "bomb" when you click one
onClick("bomb", () => {
destroyAll("bomb");
});
group
Game Obj
Base interface of all game objects.
since
v2000.0
group
Game Obj
add<T>(comps?: CompList | GameObj): GameObj<T>
Add a child.
param
comps- The components to add.
returns
The added game object.
since
v3000.0
readd<T>(obj: GameObj): GameObj<T>
Remove and re-add the game obj, without triggering add / destroy events.
param
obj- The game object to re-add.
returns
The re-added game object.
since
v3000.0
remove(obj: GameObj): void
Remove a child.
param
obj- The game object to remove.
since
v3000.0
Remove all children with a certain tag.
param
tag- The tag to remove.
since
v3000.0
Remove all children.
since
v3000.0
get(tag: Tag | Tag[], opts?: GetOpt): GameObj[]
Get a list of all game objs with certain tag.
param
tag- The tag to get.
since
v3000.0
query(opt: QueryOpt): GameObj[]
Get a list of all game objs with certain properties.
param
opt- The properties to get.
since
v3001.0
readonly
Get all children game objects.
since
v3000.0
tags: string[]
readonly
Get the tags of a game object. For update it, use `tag()` and `untag()`.
since
v3001.0
Update this game object and all children game objects.
since
v3001.0
Update this game object and all children game objects.
since
v3000.0
Draw this game object and all children game objects.
since
v3000.0
Draw debug info in inspect mode
since
v3000.0
use(comp: Comp | Tag): void
Add a component.
const obj = add([
sprite("bean"),
]);
// Add opacity
obj.use(opacity(0.5));
since
v2000.0
unuse(comp: Tag): void
Remove a component with its id (the component name)
param
comp- The component id to remove. It means the name, if sprite, then it's "sprite".
// Remove sprite component
obj.unuse("sprite");
since
v2000.0
has(compId: string | string[], op?: "and" | "or"): boolean
Check if game object has a certain component.
param
compId- The component id(s) to check.
param
op- The operator to use when searching for multiple components. Default is "and".
// Check if game object has sprite component
if(obj.has("sprite")) {
debug.log("has sprite component");
}
// Check if game object has tags
obj.has(["tag1", "tag2"]); // AND, it has both tags
obj.has(["tag1", "tag2"], "or"); // OR, it has either tag1 or tag2
returns
true if has the component(s), false otherwise.
since
v3001.0.5
experimental
This feature is in experimental phase, it will be fully released in v4000.0
tag(tag: Tag | Tag[]): void
Add a tag(s) to the game obj.
param
tag- The tag(s) to add.
// add enemy tag
obj.tag("enemy");
// add multiple tags
obj.tag(["enemy", "boss"]);
since
v3001.0.5
experimental
This feature is in experimental phase, it will be fully released in v4000.0
untag(tag: Tag | Tag[]): void
Remove a tag(s) from the game obj.
param
tag- The tag(s) to remove.
// remove enemy tag
obj.untag("enemy");
// remove multiple tags
obj.untag(["enemy", "boss"]);
since
v3001.0.5
experimental
This feature is in experimental phase, it will be fully released in v4000.0
is(tag: Tag | Tag[], op?: "and" | "or"): boolean
If there's certain tag(s) on the game obj.
param
tag- The tag(s) for checking.
param
op- The operator to use when searching for multiple tags. Default is "and".
since
v3001.0.5
experimental
This feature is in experimental phase, it will be fully released in v4000.0
on(event: GameObjEventNames | string & {}, action: (args: any)=>void): KEventController
Register an event.
param
event- The event name.
param
action- The action to run when event is triggered.
returns
The event controller.
since
v2000.0
trigger(event: string, args: any): void
Trigger an event.
param
event- The event name.
parm
args - The arguments to pass to the event action.
since
v2000.0
Remove the game obj from scene.
since
v2000.0
c(id: string): Comp | null
Get state for a specific comp.
param
id- The component id.
since
v2000.0
inspect(): GameObjInspect
Gather debug info of all comps.
since
v2000.0
onAdd(action: ()=>void): KEventController
Register an event that runs when the game obj is added to the scene.
returns
The event controller.
since
v2000.0
onUpdate(action: ()=>void): KEventController
Register an event that runs every frame as long as the game obj exists.
returns
The event controller.
since
v2000.1
onFixedUpdate(action: ()=>void): KEventController
Register an event that runs every frame as long as the game obj exists.
returns
The event controller.
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).
returns
The event controller.
since
v2000.1
onDestroy(action: ()=>void): KEventController
Register an event that runs when the game obj is destroyed.
returns
The event controller.
since
v2000.1
onUse(action: (id: string)=>void): KEventController
Register an event that runs when a component is used.
returns
The event controller.
since
v3001.0
onUnuse(action: (id: string)=>void): KEventController
Register an event that runs when a component is unused.
returns
The event controller.
since
v3001.0
onTag(action: (tag: string)=>void): KEventController
Register an event that runs when a tag is added.
returns
The event controller.
since
v3001.10
experimental
onUntag(action: (tag: string)=>void): KEventController
Register an event that runs when a tag is removed.
returns
The event controller.
since
v3001.10
experimental
If game obj is attached to the scene graph.
returns
true if attached, false otherwise.
since
v2000.0
Check if is an ancestor (recursive parent) of another game object
returns
true if is ancestor, false otherwise.
since
v3000.0
Calculated transform matrix of a game object.
since
v3000.0
If draw the game obj (run "draw" event or not).
since
v2000.0
If update the game obj (run "update" event or not).
since
v2000.0
id: GameObjID | null
A unique number ID for each game object.
since
v2000.0
canvas: FrameBuffer | null
The canvas to draw this game object on
since
v3001.0
onKeyDown: KAPLAYCtx["onKeyDown"]
onKeyPress: KAPLAYCtx["onKeyPress"]
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"]
onGamepadStick: KAPLAYCtx["onGamepadStick"]
onButtonDown: KAPLAYCtx["onButtonDown"]
onButtonPress: KAPLAYCtx["onButtonPress"]
GameObj<T>: GameObjRaw & MergeComps
The basic unit of object in KAPLAY. The player, a butterfly, a tree, or even a piece of text.
group
Game Obj
group
Game Obj
pos(x: number, y: number): PosComp
Set the position of a Game Object.
param
x- The x position to set.
param
y- The y position to set.
// This game object will draw a "bean" sprite at (100, 200)
add([
pos(100, 200),
sprite("bean"),
]);
returns
The position comp.
since
v2000.0
group
Components
pos(xy: number): PosComp
pos(p: Vec2): PosComp
pos(): PosComp
scale(x: number, y: number): ScaleComp
Set the scale of a Game Object.
param
x- The x scale to set.
param
y- The y scale to set.
// 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);
returns
The scale comp.
since
v2000.0
group
Components
scale(xy: number): ScaleComp
scale(s: Vec2): ScaleComp
scale(): ScaleComp
rotate(a?: number): RotateComp
Rotates a Game Object (in degrees).
param
a- The angle to rotate by. Defaults to 0.
let bean = add([
sprite("bean"),
rotate(),
])
// bean will be upside down!
bean.angle = 180
returns
The rotate comp.
since
v2000.0
group
Components
color(r: number, g: number, b: number): ColorComp
Sets the color of a Game Object (rgb 0-255).
param
r- The red value to set.
param
g- The green value to set.
param
b- The blue value to set.
// blue frog
add([
sprite("bean"),
color(0, 0, 255),
]);
returns
The color comp.
since
v2000.0
group
Components
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).
param
o- The opacity value to set.
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
returns
The opacity comp.
since
v2000.0
group
Components
sprite(spr: string | SpriteData | Asset, opt?: SpriteCompOpt): SpriteComp
Attach and render a sprite to a Game Object.
param
spr- The sprite to render.
param
opt- Options for the sprite component. See
// 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
returns
The sprite comp.
since
v2000.0
group
Components
text(txt?: string, opt?: TextCompOpt): TextComp
Attach and render a text to a Game Object.
param
txt- The text to display.
param
opt- 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
}),
])
returns
The text comp.
since
v2000.0
group
Components
polygon(pts: Vec2[], opt?: PolygonCompOpt): PolygonComp
Attach and render a polygon to a Game Object.
param
pts- The points to render the polygon.
param
opt- Options for the polygon component. See
// 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(),
])
returns
The polygon comp.
since
v3001.0
group
Components
rect(w: number, h: number, opt?: RectCompOpt): RectComp
Attach and render a rectangle to a Game Object.
param
w- The width of the rectangle.
param
h- The height of the rectangle.
param
opt- Options for the rectangle component. See
const obstacle = add([
pos(80, 120),
rect(20, 40),
outline(4),
area(),
])
returns
The rectangle component.
group
Components
circle(radius: number, opt?: CircleCompOpt): CircleComp
Attach and render a circle to a Game Object.
param
radius- The radius of the circle.
param
opt- Options for the circle component. See
add([
pos(80, 120),
circle(16),
])
returns
The circle comp.
since
v2000.0
group
Components
uvquad(w: number, h: number): UVQuadComp
Attach and render a UV quad to a Game Object.
param
w- The width of the quad.
param
h- The height of the quad.
add([
uvquad(width(), height()),
shader("spiral"),
])
returns
The UV quad comp.
since
v2000.0
group
Components
area(opt?: AreaCompOpt): AreaComp
Attach a collider area from shape and enables collision detection in a Game Object.
param
opt- Options for the area component. See
// 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
}
})
returns
The area comp.
since
v2000.0
group
Components
anchor(o: Anchor | Vec2): AnchorComp
Anchor point for render (default "topleft").
param
o- The anchor point to set.
// set anchor to "center" so it'll rotate from center
add([
rect(40, 10),
rotate(45),
anchor("center"),
])
returns
The anchor comp.
since
v2000.0
group
Components
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.
param
z- The z value to set.
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
returns
The z comp.
since
v2000.0
group
Components
outline(width?: number, color?: Color, opacity?: number, join?: LineJoin, miterLimit?: number, cap?: LineCap): OutlineComp
Give an object an outline. Doesn't support sprite or text components.
param
width- The width of the outline.
param
color- The color of the outline.
param
opacity- The opacity of the outline.
param
join- -The line join style.
param
miterLimit- The miter limit ratio.
param
cap-The line cap style.
// Add an outline to a rectangle
add([
rect(40, 40),
outline(4),
]);
returns
The outline comp.
since
v2000.0
group
Components
particles(popt: ParticlesOpt, eopt: EmitterOpt): ParticlesComp
Attach a particle emitter to a Game Object.
param
popt- The options for the particles.
param
eopt- 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)
})
returns
The particles comp.
since
v3001.0
group
Components
body(opt?: BodyCompOpt): BodyComp
Physical body that responds to gravity. Requires "area" and "pos" comp. This also makes the object "solid".
param
opt- Options for the body component. See
// 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!")
})
returns
The body comp.
since
v2000.0
group
Components
surfaceEffector(opt: SurfaceEffectorCompOpt): SurfaceEffectorComp
Applies a force on a colliding object in order to make it move along the collision tangent vector.
Good for conveyor belts.
param
opt- Options for the surface effector component. See
loadSprite("belt", "/sprites/jumpy.png")
// conveyor belt
add([
pos(center()),
sprite("belt"),
rotate(90),
area(),
body({ isStatic: true }),
surfaceEffector({
speed: 50,
})
])
returns
The surface effector comp.
since
v3001.0
group
Components
areaEffector(opt: AreaEffectorCompOpt): AreaEffectorComp
Applies a force on a colliding object.
Good to apply anti-gravity, wind or water flow.
param
opt- Options for the area effector component. See
returns
The area effector comp.
since
v3001.0
group
Components
pointEffector(opt: PointEffectorCompOpt): PointEffectorComp
Applies a force on a colliding object directed towards this object's origin.
Good to apply magnetic attraction or repulsion.
param
opt- Options for the point effector component. See
returns
The point effector comp.
since
v3001.0
group
Components
platformEffector(opt?: PlatformEffectorCompOpt): PlatformEffectorComp
The platform effector makes it easier to implement one way platforms
or walls. This effector is typically used with a static body, and it
will only be solid depending on the direction the object is traveling from.
param
opt- Options for the platform effector component. See
returns
The platform effector comp.
since
v3001.0
group
Components
buoyancyEffector(opt: 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.
param
opt- Options for the buoyancy effector component. See
returns
The buoyancy effector comp.
since
v3001.0
group
Components
constantForce(opt: ConstantForceCompOpt): ConstantForceComp
Applies a constant force to the object.
Good to apply constant thrust.
param
opt- Options for the constant force component. See
returns
The constant force comp.
since
v3001.0
group
Components
doubleJump(numJumps?: number): DoubleJumpComp
Enables double jump.
param
numJumps- The number of jumps allowed. Defaults to 1.
requires
returns
The double jump comp.
since
v3000.0
group
Components
move(dir: number | Vec2, speed: number): EmptyComp
Move towards a direction infinitely, and destroys when it leaves game view.
param
dir- The direction to move towards.
param
speed- The speed to move at.
requires
// enemy throwing feces at player
const projectile = add([
sprite("feces"),
pos(enemy.pos),
area(),
move(player.pos.angle(enemy.pos), 1200),
offscreen({ destroy: true }),
])
returns
The move comp.
since
v2000.0
group
Components
offscreen(opt?: OffScreenCompOpt): OffScreenComp
Control the behavior of object when it goes out of view.
param
opt- Options for the offscreen component. See
add([
pos(player.pos),
sprite("bullet"),
offscreen({ destroy: true }),
"projectile",
]);
returns
The offscreen comp.
since
v2000.2
group
Components
follow(obj: GameObj | null, offset?: Vec2): FollowComp
Follow another game obj's position.
param
obj- The game obj to follow.
param
offset- The offset to follow at.
const bean = add(...)
add([
sprite("bag"),
pos(),
follow(bean) // Follow bean's position
]);
// Using offset
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
returns
The follow comp.
since
v2000.0
group
Components
shader(id: string, uniform?: Uniform | ()=>Uniform): ShaderComp
Custom shader.
param
id- The shader id.
param
uniform- The uniform to pass to the shader.
returns
The shader comp.
since
v2000.0
group
Components
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.
param
hasFocus- Whether the text input should have focus.
param
maxInputLength- The maximum length of the input.
const obj = add([
text(""),
textInput(),
])
obj.hasFocus = false
debug.log(obj.text) // oh no i cant see my new text since it was disabled
returns
The text input comp.
since
v3001.0
group
Components
timer(maxLoopsPerFrame?: number): TimerComp
Enable timer related functions like wait(), loop(), tween() on the game object.
param
maxLoopsPerFrame- The maximum number of loops per frame.
const obj = add([
timer(),
])
obj.wait(2, () => { ... })
obj.loop(0.5, () => { ... })
obj.tween(obj.pos, mousePos(), 0.5, (p) => obj.pos = p, easings.easeOutElastic)
returns
The timer comp.
since
v2000.0
group
Components
fixed(): FixedComp
Make a game obj unaffected by camera or parent object transforms, and render at last.
Useful for UI elements.
// this will be be fixed on top left and not affected by camera
const score = add([
text(0),
pos(12, 12),
fixed(),
])
returns
The fixed comp.
since
v2000.0
group
Components
stay(scenesToStay?: string[]): StayComp
Don't get destroyed on scene switch. Only works in objects attached to root.
param
scenesToStay- The scenes to stay in. By default it stays in all scenes.
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)
})
returns
The stay comp.
since
v2000.0
group
Components
health(hp: number, maxHP?: number): HealthComp
Handles health related logic and events.
param
hp- The initial health points.
param
maxHP- The maximum health points.
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")
})
returns
The health comp.
since
v2000.0
group
Components
lifespan(time: number, options?: LifespanCompOpt): EmptyComp
Destroy the game obj after certain amount of time
param
time- The time to live.
param
options- Options for the lifespan component. See
// spawn an explosion, destroy after 1.5 seconds (time + fade)
add([
sprite("explosion", { anim: "burst", }),
lifespan(1, {
fade: 0.5 // it start fading 0.5 second after time
}),
]);
returns
The lifespan comp.
since
v2000.0
group
Components
named(name: string): NamedComp
Names an game obj.
param
name- The name to set.
returns
The named comp.
since
v3001.0
group
Components
state(initialState: string, stateList?: string[]): StateComp
Finite state machine.
param
initialState- The initial state.
param
stateList- The list of states.
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")
}
})
returns
The state comp.
since
v2000.1
group
Components
state(initialState: string, stateList: string[], transitions: Record): StateComp
state() with pre-defined transitions.
param
initialState- The initial state.
param
stateList- The list of states.
param
transitions- The transitions between states.
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)
})
returns
The state comp.
since
v2000.2
group
Components
fadeIn(time: number): Comp
deprecated
since v3001.0
requires
returns
An empty comp.
since
v3000.0
group
Components
mask(maskType?: Mask): MaskComp
Mask all children object render.
param
maskType- The type of mask to use.
returns
The mask comp.
since
v3001.0
group
Components
drawon(canvas: FrameBuffer): Comp
Specifies the FrameBuffer the object should be drawn on.
param
canvas- The FrameBuffer to draw on.
// Draw on another canvas
let canvas = makeCanvas(width(), height());
let beanOnCanvas = add([
sprite("bean"),
drawon(canvas.fb),
]);
returns
The drawon comp.
since
v3000.0
group
Components
tile(opt?: TileCompOpt): TileComp
A tile on a tile map.
param
opt- Options for the tile component. See
returns
The tile comp.
since
v3000.0
group
Components
agent(opt?: AgentCompOpt): AgentComp
An agent which can finds it way on a tilemap.
param
opt- Options for the agent component. See
returns
The agent comp.
since
v3000.0
group
Components
animate(opt?: AnimateCompOpt): AnimateComp
A component to animate properties.
param
opt- Options for the animate component. See
let movingBean = add([
sprite("bean"),
pos(50, 150),
anchor("center"),
animate(),
]);
// Moving right to left using ping-pong
movingBean.animate("pos", [vec2(50, 150), vec2(150, 150)], {
duration: 2,
direction: "ping-pong",
});
returns
The animate comp.
since
v3001.0
group
Components
serializeAnimation(obj: GameObj, name: string): Animation
Serializes the animation to plain objects
param
obj- The game obj to serialize.
returns
The serialized animation.
since
v3001.0
group
Components
sentry(candidates: SentryCandidates, opt?: SentryCompOpt): SentryComp
A sentry which reacts to objects coming into view.
returns
The sentry comp.
since
v3001.0
group
Components
patrol(opts: PatrolCompOpt): PatrolComp
A patrol which can follow waypoints to a goal.
param
opts- Options for the patrol component. See
const bean = add([
sprite("bean"),
pos(40, 30),
patrol({
waypoints: [
vec2(100, 100),
vec2(120, 170),
vec2(50, 50),
vec2(300, 100),
],
}),
]);
bean.onPatrolFinished(gb => {
// Note that the position doesn't exactly match the last waypoint,
// this is an approximation.
debug.log(`Bean reached the end of the patrol at ${gb.pos.x}, ${gb.pos.y}`);
});
returns
The patrol comp.
since
v3001.0
group
Components
pathfinder(opts: PathfinderCompOpt): PathfinderComp
A navigator pathfinder which can calculate waypoints to a goal.
since
v3001.0
group
Components
group
Components
id?: Tag
Component ID (if left out won't be treated as a comp).
What other comps this comp depends on.
add?(): void
Event that runs when host game obj is added to scene.
Event that runs at a fixed frame rate.
Event that runs every frame.
draw?(): void
Event that runs every frame after update.
Event that runs when obj is removed from scene.
inspect?(): string | null
Debug info for inspect mode.
Draw debug info in inspect mode
since
v3000.0
The circle component.
group
Component Types
draw: Comp["draw"]
Radius of circle.
Render area of the circle.
since
v3000.0
Options for the circle component.
group
Component Types
fill?: boolean
If fill the circle (useful if you only want to render outline with
outline component).
The color component.
group
Component Types
The mask component.
group
Component Types
The opacity component.
group
Component Types
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.
The outline component.
group
Component Types
Options for the particles's component
group
Component Types
ParticlesComp:
The particles component.
group
Component Types
emit(n: number): void
onEnd(cb: ()=>void): void
PolygonComp:
The polygon component.
since
v3001.0
group
Component Types
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.
group
Component Types
RectComp:
The rect component.
group
Component Types
draw: Comp["draw"]
width: number
Width of rectangle.
height: number
Height of rectangle.
radius?: number |
[
number, number, number, number
]
The radius of each corner.
renderArea(): Rect
since
v3000.0
RectCompOpt:
Options for the rect component.
group
Component Types
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).
ShaderComp:
The shader component.
group
Component Types
uniform?: Uniform
Uniform values to pass to the shader.
shader: string
The shader ID.
SpriteComp:
The sprite component.
group
Component Types
draw: Comp["draw"]
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.
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.
group
Component Types
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.
group
Component Types
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.
group
Component Types
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
indentAll?: boolean
If true, any (whitespace) indent on the first line of the paragraph
will be copied to all of the lines for those parts that text-wrap.
UVQuadComp:
The uvquad component.
group
Component Types
draw: Comp["draw"]
width: number
Width of rect.
height: number
Height of height.
renderArea(): Rect
since
v3000.0
AgentComp:
The agent component.
group
Component Types
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
Options for the agent component.
group
Component Types
FixedComp:
The fixed component.
group
Component Types
fixed: boolean
If the obj is unaffected by camera
PosComp:
The pos component.
group
Component Types
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(newPos?: Vec2): Vec2 | null
Get / Set the position of the object on the screen.
since
v2000.0
worldPos(newPos?: Vec2): Vec2 | null
Get / Set the position of the object relative to the root.
since
v2000.0
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 other
since
v3001.0
fromOther(this: GameObj, other: GameObj, p: Vec2): Vec2
Transform a point relative to other to a point relative to this
since
v3001.0
SentryComp:
The sentry component.
group
Component Types
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
cbThe 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
objThe object to test.
param
directionThe direction to look at.
param
fieldOfViewThe field of view in degrees.
hasLineOfSight(obj: GameObj): boolean
Returns true if there is a line of sight to the object.
param
objThe object to test.
SentryCompOpt:
Options for the sentry component.
group
Component Types
direction?: Vec2 | number
fieldOfView?: number
lineOfSight?: boolean
raycastExclude?: string[]
checkFrequency?: number
TileComp:
The tile component.
group
Component Types
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>
tileMove(dir: Vec2): void
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`.
Options for the tile component.
group
Component Types
HealthComp:
The health component.
group
Component Types
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.
group
Component Types
fade?: number
Fade out duration (default 0 which is no fade out).
NamedComp:
The named component.
group
Component Types
StateComp:
The state component.
group
Component Types
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.
group
Component Types
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 textInput component.
group
Component Types
hasFocus: boolean
Enable the text input array from being modified by user input.
typedText: string
The "real" text that the user typed, without any escaping.
TimerComp:
The timer component.
group
Component Types
maxLoopsPerFrame: number
The maximum number of loops per frame allowed,
to keep loops with sub-frame intervals from freezing the game.
wait(time: number, action?: ()=>void): TimerController
Run the callback after n seconds.
loop(time: number, action: ()=>void, maxLoops?: number, waitFirst?: boolean): TimerController
Run the callback every n seconds.
If waitFirst is false (the default), the function will
be called once on the very next frame, and then loop like normal.
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.
group
Component Types
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.
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): KEventController
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): KEventController
Register an event runs once when collide with another game obj with certain tag.
since
v2001.0
onCollide(f: (obj: GameObj, col?: Collision)=>void): KEventController
Register an event runs once when collide with another game obj.
since
v2000.1
onCollideUpdate(tag: Tag, f: (obj: GameObj, col?: Collision)=>KEventController): 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.
group
Component Types
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.
group
Component Types
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, it won't move, all non static objects won't move past it, and all
calls to addForce(), applyImpulse(), or jump() on this body will do absolutely nothing.
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 impulse
param
impulseThe impulse vector, applied directly
addForce(force: Vec2): void
Applies a force
param
forceThe 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.
group
Component Types
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, it won't move, all non static objects won't move past it, and all
calls to addForce(), applyImpulse(), or jump() on this body will do absolutely nothing.
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.
group
Component Types
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.
group
Component Types
anchor: Anchor | Vec2
Anchor point for render.
FollowComp:
The follow component.
group
Component Types
follow: obj: GameObj
The object to follow.
offset: Vec2
The offset to follow the object by.
LayerComp:
The layer component.
group
Component Types
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.
group
Component Types
offscreenDistance: number | undefined
The minimum distance that the object must be off the screen by to be considered "offscreen".
If it is undefined, it means that the object will be considered to be offscreen when its bounding rectangle
(defined by width and height) is not intersecting with the screen rectangle.
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.
group
Component Types
hide?: boolean
If hide object when out of view.
pause?: boolean
If pause object when out of view.
unpause?: boolean
If unpause object when back in 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.
group
Component Types
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.
group
Component Types
scale: Vec2
The current scale of the object
returns
The 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.
group
Component Types
z: number
Defines the z-index of this game obj
MergeComps<T>: Omit<MergeObj, TypeOperator>
A type to merge the components of a game object, omitting the default component properties.
group
Component Types
CompList<T>: Array<T | Tag>
A component list.
group
Component Types
EmptyComp: id: string
& Comp
A component without own properties.
group
Component Types
LevelComp:
A level component.
group
Component Types
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[][]
removeFromSpatialMap(obj: GameObj): void
insertIntoSpatialMap(obj: GameObj): void
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
group
Scene
scene(name: SceneName, def: SceneDef): void
Define a scene.
param
name- The scene name.
param
def- The scene definition.
// define a scene
scene("game", () => {
// ...
});
// get options
scene("game", (opts) => {
debug.log(opts.level);
});
group
Scene
go(name: SceneName, args: any): void
Go to a scene, passing all rest args to scene callback.
param
name- The scene name.
param
args- The rest args to pass to the scene callback.
// go to "game" scene
go("game");
// go with options
go("game", { level: 1 });
since
v2000.0
group
Scene
layers(layers: string[], defaultLayer: string): void
param
layers- The layer names.
param
defaultLayer- The default layer name.
deprecated
Use
setLayers(["bg", "obj", "ui"], "obj")
// no layer specified, will be added to "obj"
add([
sprite("bean"),
]);
// add to "bg" layer
add([
sprite("bg"),
layer("bg"),
]);
since
v3001.0
group
Scene
onGamepadConnect(action: (gamepad: KGamepad)=>void): void
Register an event that runs when a gamepad is connected.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v3000.0
group
Input
onGamepadDisconnect(action: (gamepad: KGamepad)=>void): void
Register an event that runs when a gamepad is disconnected.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v3000.0
group
Input
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).
param
tag- The tag to listen for.
param
action- The function to run when the event is triggered.
// click on any "chest" to open
onClick("chest", (chest) => chest.open())
returns
The event controller.
since
v2000.1
group
Input
onClick(action: ()=>void): KEventController
Register an event that runs when users clicks.
param
action- The function to run when the event is triggered.
// click on anywhere to go to "game" scene
onClick(() => go("game"));
returns
The event controller.
since
v2000.1
group
Events
onKeyDown(key: Key | Key[], action: (key: Key)=>void): KEventController
Register an event that runs every frame when a key is held down.
param
key- The key(s) to listen for.
param
action- The function to run when the event is triggered.
// move left by SPEED pixels per frame every frame when left arrow key is being held down
onKeyDown("left", () => {
bean.move(-SPEED, 0)
});
returns
The event controller.
since
v2000.1
group
Input
onKeyDown(action: (key: Key)=>void): KEventController
Register an event that runs every frame when any key is held down.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v2000.1
group
Input
onKeyPress(key: Key | Key[], action: (key: Key)=>void): KEventController
Register an event that runs when user presses certain keys.
param
key- The key(s) to listen for.
param
action- The function to run when the event is triggered.
// .jump() once when "space" is just being pressed
onKeyPress("space", () => {
bean.jump();
});
onKeyPress(["up", "space"], () => {
bean.jump();
});
returns
The event controller.
since
v2000.1
group
Input
onKeyPress(action: (key: Key)=>void): KEventController
Register an event that runs when user presses any key.
param
action- The function to run when the event is triggered.
// Call restart() when player presses any key
onKeyPress((key) => {
debug.log(`key pressed ${key}`);
restart();
});
returns
The event controller.
since
v3001.0
group
Input
onKeyPressRepeat(k: Key | Key[], action: (k: Key)=>void): KEventController
Register an event that runs when user presses certain keys (also fires repeatedly when the keys are being held down).
param
k- The key(s) to listen for.
param
action- The function to run when the event is triggered.
// delete last character when "backspace" is being pressed and held
onKeyPressRepeat("backspace", () => {
input.text = input.text.substring(0, input.text.length - 1);
});
returns
The event controller.
since
v3000.1
group
Input
onKeyPressRepeat(action: (k: Key)=>void): KEventController
onKeyRelease(k: Key | Key[], action: (k: Key)=>void): KEventController
Register an event that runs when user release certain keys.
param
k- The key(s) to listen for.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v2000.1
group
Input
onKeyRelease(action: (k: Key)=>void): KEventController
onCharInput(action: (ch: string)=>void): KEventController
Register an event that runs when user inputs text.
param
action- The function to run when the event is triggered.
// type into input
onCharInput((ch) => {
input.text += ch
})
returns
The event controller.
since
v2000.1
group
Input
onMouseDown(btn: MouseButton | MouseButton[], action: (m: MouseButton)=>void): KEventController
Register an event that runs every frame when certain mouse buttons are being held down.
param
btn- The button(s) to listen for.
returns
The event controller.
since
v3001.0
group
Input
onMouseDown(action: (m: MouseButton)=>void): KEventController
onMousePress(action: (m: MouseButton)=>void): KEventController
Register an event that runs when user clicks mouse.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v3001.0
group
Input
onMousePress(btn: MouseButton | MouseButton[], action: (m: MouseButton)=>void): KEventController
onMouseRelease(action: (m: MouseButton)=>void): KEventController
Register an event that runs when user releases mouse.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v3001.0
group
Input
onMouseRelease(btn: MouseButton | MouseButton[], action: (m: MouseButton)=>void): KEventController
onMouseMove(action: (pos: Vec2, delta: Vec2)=>void): KEventController
Register an event that runs whenever user move the mouse.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v2000.1
group
Input
onTouchStart(action: (pos: Vec2, t: Touch)=>void): KEventController
Register an event that runs when a touch starts.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v2000.1
group
Input
onTouchMove(action: (pos: Vec2, t: Touch)=>void): KEventController
Register an event that runs whenever touch moves.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v2000.1
group
Input
onTouchEnd(action: (pos: Vec2, t: Touch)=>void): KEventController
Register an event that runs when a touch ends.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v2000.1
group
Input
onScroll(action: (delta: Vec2)=>void): KEventController
Register an event that runs when mouse wheel scrolled.
param
action- The function to run when the event is triggered.
// Zoom camera on scroll
onScroll((delta) => {
const zoom = delta.y / 500;
camScale(camScale().add(zoom));
});
returns
The event controller.
since
v3000.0
group
Input
onGamepadButtonDown(btn: KGamepadButton | KGamepadButton[], action: (btn: KGamepadButton, gamepad: KGamepad)=>void): KEventController
Register an event that runs every frame when certain gamepad buttons are held down.
param
btn- The button(s) to listen for.
param
action- The function to run when the event is triggered.
return
The event controller.
since
v3001.0
group
Input
onGamepadButtonDown(action: (btn: KGamepadButton, gamepad: KGamepad)=>void): KEventController
Register an event that runs every frame when any gamepad buttons are held down.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v3001.0
group
Input
onGamepadButtonPress(btn: KGamepadButton | KGamepadButton[], action: (btn: KGamepadButton, gamepad: KGamepad)=>void): KEventController
Register an event that runs when user presses certain gamepad button.
param
btn- The button(s) to listen for.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v3001.0
group
Input
onGamepadButtonPress(action: (btn: KGamepadButton, gamepad: KGamepad)=>void): KEventController
Register an event that runs when user presses any gamepad button.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v3001.0
group
Input
onGamepadButtonRelease(btn: KGamepadButton | KGamepadButton[], action: (btn: KGamepadButton, gamepad: KGamepad)=>void): KEventController
Register an event that runs when user releases certain gamepad button
param
btn- The button(s) to listen for.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v3001.0
group
Input
onGamepadButtonRelease(action: (btn: KGamepadButton, gamepad: KGamepad)=>void): KEventController
Register an event that runs when user releases any gamepad button.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v3000.0
group
Input
onGamepadStick(stick: GamepadStick, action: (value: Vec2, gameepad: KGamepad)=>void): KEventController
Register an event that runs when the gamepad axis exists.
param
stick- The stick to listen for.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v3000.0
group
Input
onButtonPress(btn: TButton | TButton[], action: (btn: TButton)=>void): KEventController
Register an event that runs when user press a defined button
(like "jump") on any input (keyboard, gamepad).
param
btn- The button(s) to listen for.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v3001.0
group
Input
onButtonRelease(btn: TButton | TButton[], action: (btn: TButton)=>void): KEventController
Register an event that runs when user release a defined button
(like "jump") on any input (keyboard, gamepad).
param
btn- The button(s) to listen for.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v3001.0
group
Input
onButtonRelease(action: (btn: TButton)=>void): KEventController
onButtonDown(btn: TButton | TButton[], action: (btn: TButton)=>void): KEventController
Register an event that runs when user press a defined button
(like "jump") on any input (keyboard, gamepad).
param
btn- The button(s) to listen for.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v3001.0
group
Input
onButtonDown(action: (btn: TButton)=>void): KEventController
isTouchscreen(): boolean
Is currently on a touch screen device.
returns
true if on a touch screen device.
since
v3000.0
group
Input
mousePos(): Vec2
Get current mouse position (without camera transform).
returns
The current mouse position.
since
v2000.0
group
Input
mouseDeltaPos(): Vec2
How much mouse moved last frame.
returns
The delta mouse position.
since
v2000.0
group
Input
isKeyDown(k?: Key | Key[]): boolean
If any or certain key(s) are currently down.
param
k- The key(s) to check.
// Any key down
let lastKeyTime = time()
let triedToWakeUp = false
onUpdate(() => {
if (isKeyDown()) {
lastKeyTime = time()
triedToWakeUp = false
return
}
if (triedToWakeUp || time() - lastKeyTime < 5) return
debug.log("Wake up!")
triedToWakeUp = true
})
// Certain key down
// equivalent to the calling bean.move() in an onKeyDown("left")
onUpdate(() => {
if (isKeyDown("left")) {
bean.move(-SPEED, 0)
}
})
// Certain keys down
let isMoving = false
onUpdate(() => {
isMoving = isKeyDown(["left", "right"])
})
since
v2000.0
group
Input
isKeyPressed(k?: Key | Key[]): boolean
If any or certain key(s) are just pressed last frame.
param
k- The key(s) to check.
onUpdate(() => {
if (!isKeyPressed()) return // early return as no key was pressed
if (isKeyPressed("space")) debug.log("Pressed the jump key")
if (isKeyPressed(["left", "right"])) debug.log("Pressed any of the move keys")
})
since
v2000.0
group
Input
isKeyPressedRepeat(k?: Key | Key[]): boolean
If any or certain key(s) are just pressed last frame (also fires repeatedly when the keys are being held down).
param
k- The key(s) to check.
let heldKeys = new Set()
onUpdate(() => {
if (isKeyPressedRepeat("space")) {
pressedOrHeld(["space"], 'the jump key')
} else if (isKeyPressedRepeat(["left", "right"])) {
pressedOrHeld(["left", "right"], 'any of the move keys')
} else if (isKeyPressedRepeat()) {
pressedOrHeld(["any"], 'any key')
}
})
onKeyRelease((key) => wait(0.1, () => {
heldKeys.delete(key)
heldKeys.delete("any")
}))
// log message if pressed only or held as well
function pressedOrHeld(keys, string) {
debug.log(`Pressed${keys.some(key => heldKeys.has(key)) ? ' and held' : ''} ${string}`)
keys.forEach((key) => {
if (key == "any" || isKeyDown(key)) heldKeys.add(key)
})
}
since
v2000.0
group
Input
isKeyReleased(k?: Key | Key[]): boolean
If any or certain key(s) are just released last frame.
param
k- The key(s) to check.
onUpdate(() => {
if (!isKeyReleased()) return // early return as no key was released
if (isKeyReleased("space")) debug.log("Released the jump key")
if (isKeyReleased(["left", "right"])) debug.log("Released any of the move keys")
})
since
v2000.0
group
Input
isMouseDown(btn?: MouseButton | MouseButton[]): boolean
If mouse buttons are currently down.
param
btn- The button(s) to check.
since
v2000.0
group
Input
isMousePressed(btn?: MouseButton | MouseButton[]): boolean
If mouse buttons are just clicked last frame
param
btn- The button(s) to check.
since
v2000.0
group
Input
isMouseReleased(btn?: MouseButton | MouseButton[]): boolean
If mouse buttons are just released last frame.
param
btn- The button(s) to check.
since
v2000.0
group
Input
isMouseMoved(): boolean
If mouse moved last frame.
since
v2000.1
group
Input
isGamepadButtonPressed(btn?: KGamepadButton | KGamepadButton[]): boolean
If certain gamepad buttons are just pressed last frame
param
btn- The button(s) to check.
since
v3000.0
group
Input
isGamepadButtonDown(btn?: KGamepadButton | KGamepadButton): boolean
If certain gamepad buttons are currently held down.
param
btn- The button(s) to check.
since
v3000.0
group
Input
isGamepadButtonReleased(btn?: KGamepadButton | KGamepadButton[]): boolean
If certain gamepad buttons are just released last frame.
param
btn- The button(s) to check.
since
v3000.0
group
Input
isButtonPressed(btn?: TButton | TButton[]): boolean
If any or certain bound button(s) are just pressed last frame on any input (keyboard, gamepad).
param
btn- The button(s) to check.
onUpdate(() => {
if (!isButtonPressed()) return // early return as no button was pressed
if (isButtonPressed("jump")) debug.log("Player jumped")
if (isButtonPressed(["left", "right"])) debug.log("Player moved")
})
since
v3001.0
group
Input
isButtonDown(btn?: TButton | TButton[]): boolean
If any or certain bound button(s) are currently held down on any input (keyboard, gamepad).
param
btn- The button(s) to check.
onUpdate(() => {
if (!isButtonDown()) return // early return as no button is held down
if (isButtonDown("jump")) debug.log("Player is jumping")
if (isButtonDown(["left", "right"])) debug.log("Player is moving")
})
since
v3001.0
group
Input
isButtonReleased(btn?: TButton | TButton[]): boolean
If any or certain bound button(s) are just released last frame on any input (keyboard, gamepad).
param
btn- The button(s) to check.
onUpdate(() => {
if (!isButtonReleased()) return // early return as no button was released
if (isButtonReleased("jump")) debug.log("Player stopped jumping")
if (isButtonReleased(["left", "right"])) debug.log("Player stopped moving")
})
since
v3001.0
group
Input
getButton(btn: TypeOperator): ButtonBinding
Get a input binding from a button name.
param
btn- The button to get binding for.
since
v3001.0
group
Input
setButton(btn: string, def: ButtonBinding): void
Set a input binding for a button name.
param
btn- The button to set binding for.
since
v3001.0
group
Input
pressButton(btn: TButton): void
Press a button virtually.
param
btn- The button to press.
// press "jump" button
pressButton("jump"); // triggers onButtonPress, starts onButtonDown
releaseButton("jump"); // triggers onButtonRelease, stops onButtonDown
since
v3001.0
group
Input
releaseButton(btn: TButton): void
Release a button virtually.
param
btn- The button to release.
// press "jump" button
pressButton("jump"); // triggers onButtonPress, starts onButtonDown
releaseButton("jump"); // triggers onButtonRelease, stops onButtonDown
since
v3001.0
group
Input
getGamepadStick(stick: GamepadStick): Vec2
Get stick axis values from a gamepad.
param
stick- The stick to get values from.
returns
The stick axis Vec2.
since
v3001.0
group
Input
getLastInputDeviceType(): ButtonBindingDevice | null
Get the latest input device type that triggered the input event.
returns
The last input device type, or null if no input event has been triggered.
since
v3001.0
group
Input
charInputted(): string[]
List of characters inputted since last frame.
returnns
An array of characters inputted.
since
v3000.0
group
Input
Key: "f1" | "f2" | "f3" | "f4" | "f5" | "f6" | "f7" | "f8" | "f9" | "f10" | "f11" | "f12" | "`" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "0" | "-" | "+" | "=" | "q" | "w" | "e" | "r" | "t" | "y" | "u" | "i" | "o" | "p" | "[" | "]" | "\" | "a" | "s" | "d" | "f" | "g" | "h" | "j" | "k" | "l" | ";" | "'" | "z" | "x" | "c" | "v" | "b" | "n" | "m" | "," | "." | "/" | "escape" | "backspace" | "enter" | "tab" | "control" | "alt" | "meta" | "space" | " " | "left" | "right" | "up" | "down" | "shift" | string & {}
A key.
group
Input
MouseButton: "left" | "right" | "middle" | "back" | "forward"
A mouse button.
group
Input
KGamepadButton: "north" | "east" | "south" | "west" | "ltrigger" | "rtrigger" | "lshoulder" | "rshoulder" | "select" | "start" | "lstick" | "rstick" | "dpad-up" | "dpad-right" | "dpad-down" | "dpad-left" | "home" | "capture"
A gamepad button.
group
Input
GamepadStick: "left" | "right"
A gamepad stick.
group
Input
KEventController:
A controller for all events in KAPLAY.
// Create a new event
const logHi = onUpdate(() => {
debug.log("hi");
});
// Pause the event
logHi.paused = true;
// Cancel the event
logHi.cancel();
group
Events
paused: boolean
If the event is paused
cancel(): void
Cancel the event
join(events: KEventController[]): KEventController
replace(oldEv: KEventController, newEv: KEventController): KEventController
GameObjEventMap: {}
Game Object events with their arguments.
If looking for use it with `obj.on()`, ignore first parameter (Game Obj)
group
Events
trigger(event: string, tag: string, args: any): void
Trigger an event on all game objs with certain tag.
param
event- The tag to trigger to.
param
tag- Arguments to pass to the `on()` functions
trigger("shoot", "target", 140);
on("shoot", "target", (obj, score) => {
obj.destroy();
debug.log(140); // every bomb was 140 score points!
});
since
v3001.0.6
group
Events
experimental
This feature is in experimental phase, it will be fully released in v3001.1.0
on<Ev>(event: Ev, tag: Tag, action: (obj: GameObj, args: TupleWithoutFirst)=>void): KEventController
Register an event on all game objs with certain tag.
param
event- The tag to listen for.
param
tag- The function to run when the event is triggered.
// a custom event defined by body() comp
// every time an obj with tag "bomb" hits the floor, destroy it and addKaboom()
on("ground", "bomb", (bomb) => {
destroy(bomb)
addKaboom(bomb.pos)
})
// a custom event can be defined manually
// by passing an event name, a tag, and a callback function
// if you want any tag, use a tag of "*"
on("talk", "npc", (npc, message) => {
npc.add([
text(message),
pos(0, -50),
lifespan(2),
opacity(),
])
});
onKeyPress("space", () => {
// the trigger method on game objs can be used to trigger a custom event
npc.trigger("talk", "Hello, KAPLAY!");
});
returns
The event controller.
since
v2000.0
group
Events
onFixedUpdate(action: ()=>void): KEventController
Register an event that runs at a fixed framerate.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v3001.0
group
Events
onFixedUpdate(tag: Tag, action: (obj: GameObj)=>void): KEventController
onUpdate(tag: Tag, action: (obj: GameObj)=>void): KEventController
Register an event that runs every frame (~60 times per second) for all game objs with certain tag.
param
tag- The tag to listen for.
param
action- The function to run when the event is triggered.
// move every "tree" 120 pixels per second to the left, destroy it when it leaves screen
// there'll be nothing to run if there's no "tree" obj in the scene
onUpdate("tree", (tree) => {
tree.move(-120, 0)
if (tree.pos.x < 0) {
destroy(tree)
}
})
returns
The event controller.
since
v2000.1
group
Events
onUpdate(action: ()=>void): KEventController
Register an event that runs every frame (~60 times per second).
param
action- The function to run when the event is triggered.
// This will run every frame
onUpdate(() => {
debug.log("ohhi")
})
returns
The event controller.
since
v2000.1
group
Events
onDraw(tag: Tag, action: (obj: GameObj)=>void): KEventController
Register an event that runs every frame (~60 times per second) for all game objs with certain tag (this is the same as onUpdate but all draw events are run after update events, drawXXX() functions only work in this phase).
param
tag- The tag to listen for.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v2000.1
group
Events
onDraw(action: ()=>void): KEventController
Register an event that runs every frame (~60 times per second) (this is the same as onUpdate but all draw events are run after update events, drawXXX() functions only work in this phase).
onDraw(() => {
drawLine({
p1: vec2(0),
p2: mousePos(),
color: rgb(0, 0, 255),
})
})
returns
The event controller.
since
v2000.1
group
Events
onAdd(tag: Tag, action: (obj: GameObj)=>void): KEventController
Register an event that runs when a game obj with certain tag is created.
param
tag- The tag to listen for.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v2000.0
group
Events
onAdd(action: (obj: GameObj)=>void): KEventController
Register an event that runs when a game obj is created.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v2000.0
group
Events
onDestroy(tag: Tag, action: (obj: GameObj)=>void): KEventController
Register an event that runs when a game obj with certain tag is destroyed.
param
tag- The tag to listen for.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v2000.0
group
Events
onDestroy(action: (obj: GameObj)=>void): KEventController
Register an event that runs when a game obj is destroyed.
param
action- The function to run when the event is triggered.
returns
The event controller.
group
Events
onUse(action: (obj: GameObj, id: string)=>void): KEventController
Register an event that runs when an object starts using a component.
param
action- The function that runs when an object starts using component.
param
unknown- The id of the component that was added.
returns
The event controller.
since
v3001.10
group
Events
onUnuse(action: (obj: GameObj, id: string)=>void): KEventController
Register an event that runs when an object stops using a component.
param
action- The function that runs when an object stops using a component.
param
unknown- The id of the component that was removed.d
returns
The event controller.
since
v3001.10
group
Events
onTag(action: (obj: GameObj, tag: string)=>void): KEventController
Register an event that runs when an object gains a tag.
param
action- The function that runs when an object gains a tag.
param
unknown- The tag which was added.
returns
The event controller.
since
v3001.10
group
Events
onUntag(action: (obj: GameObj, tag: string)=>void): KEventController
Register an event that runs when an object loses a tag.
param
action- The function that runs when an object loses a tag.
param
unknown- The tag which was removed.
returns
The event controller.
since
v3001.10
group
Events
onLoad(action: ()=>void): void
Register an event that runs when all assets finished loading.
param
action- The function to run when the event is triggered.
const bean = add([
sprite("bean"),
])
// certain assets related data are only available when the game finishes loading
onLoad(() => {
debug.log(bean.width)
})
returns
The event controller.
since
v2000.1
group
Events
onLoadError(action: (name: string, failedAsset: Asset)=>void): KEventController | undefined
Register an event that runs once for each asset that failed to load,
after all others have completed.
param
actionThe function to run when the event is triggered.
// this will not load
loadSprite("bobo", "notavalidURL");
// process the error
// you decide whether to ignore it, or throw an error and halt the game
onLoadError((name, asset) => {
debug.error(`${name} failed to load: ${asset.error}`);
})
returns
The event controller.
since
v3001.0
group
Events
onLoading(action: (progress: number)=>void): void
Register an event that runs every frame when assets are initially loading. Can be used to draw a custom loading screen.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v3000.0
group
Events
onError(action: (err: Error)=>void): void
Register a custom error handler. Can be used to draw a custom error screen.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v3000.0
group
Events
onResize(action: ()=>void): void
Register an event that runs when the canvas resizes.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v3000.0
group
Events
onCleanup(action: ()=>void): void
Cleanup function to run when quit() is called.
param
action- The function to run when the event is triggered.
since
v3000.0
group
Events
onCollide(t1: Tag, t2: Tag, action: (a: GameObj, b: GameObj, col?: Collision)=>void): KEventController
Register an event that runs once when 2 game objs with certain tags collides (required to have area() component).
param
t1- The tag of the first game obj.
param
t2- The tag of the second game obj.
param
action- The function to run when the event is triggered.
onCollide("sun", "earth", () => {
addExplosion()
})
returns
The event controller.
since
v2000.1
group
Events
onCollideUpdate(t1: Tag, t2: Tag, action: (a: GameObj, b: GameObj, col?: Collision)=>void): KEventController
Register an event that runs every frame when 2 game objs with certain tags collides (required to have area() component).
param
t1- The tag of the first game obj.
param
t2- The tag of the second game obj.
param
action- The function to run when the event is triggered.
onCollideUpdate("sun", "earth", () => {
debug.log("okay this is so hot");
})l
returns
The event controller.
since
v3000.0
group
Events
onHover(tag: Tag, action: (a: GameObj)=>void): KEventController
Register an event that runs once when game objs with certain tags are hovered (required to have area() component).
param
tag- The tag to listen for.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v3000.0
group
Events
onHoverUpdate(tag: Tag, action: (a: GameObj)=>void): KEventController
Register an event that runs every frame when game objs with certain tags are hovered (required to have area() component).
param
tag- The tag to listen for.
param
action- The function to run when the event is triggered.
// Rotate bean 90 degrees per second when hovered
onHoverUpdate("bean", (bean) => {
bean.angle += dt() * 90
});
returns
The event controller.
since
v3000.0
group
Events
onHoverEnd(tag: Tag, action: (a: GameObj)=>void): KEventController
Register an event that runs once when game objs with certain tags are unhovered (required to have area() component).
param
tag- The tag to listen for.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v3000.0
group
Events
onHide(action: ()=>void): KEventController
Register an event that runs when tab is hidden.
returns
The event controller.
since
v3001.0
group
Events
onShow(action: ()=>void): KEventController
Register an event that runs when tab is shown.
returns
The event controller.
since
v3001.0
group
Events
onSceneLeave(action: (newScene?: string)=>void): KEventController
Register an event that runs when current scene ends.
param
action- The function to run when the event is triggered.
returns
The event controller.
since
v3000.0
group
Events
KEvent<Args>:
cancellers:
handlers:
add(action: (args: Args)=>unknown): KEventController
addOnce(action: (args: Args | PromiseLike[])=>void): KEventController
next(): Promise<Args>
trigger(args: Args): void
numListeners(): number
clear(): void
KEventHandler<EventMap>:
handlers:
registers: Partial<MappedType>
on<Name>(name: Name, action: (args: EventMap[Name])=>void): KEventController
onOnce<Name>(name: Name, action: (args: EventMap[Name])=>void): KEventController
next<Name>(name: Name): Promise<unknown>
trigger<Name>(name: Name, args: EventMap[Name]): void
remove<Name>(name: Name): void
clear(): void
numListeners<Name>(name: Name): number
KEventController:
A controller for all events in KAPLAY.
// Create a new event
const logHi = onUpdate(() => {
debug.log("hi");
});
// Pause the event
logHi.paused = true;
// Cancel the event
logHi.cancel();
group
Events
paused: boolean
If the event is paused
cancel(): void
Cancel the event
join(events: KEventController[]): KEventController
replace(oldEv: KEventController, newEv: KEventController): KEventController
cancel(): Symbol
Cancels the event by returning the cancel symbol.
onKeyPress((key) => {
if (key === "q") return cancel();
});
returns
The cancel event symbol.
since
v3001.0.5
group
Events
experimental
This feature is in experimental phase, it will be fully released in v4000.0
width(): number
Get the width of game.
returns
The width of the game.
since
v2000.0
group
Info
getTreeRoot(): GameObj
Get the root of all objects.
returns
The root object.
since
v2000.0
group
Info
height(): number
Get the height of game.
returns
The height of the game.
since
v2000.0
group
Info
center(): Vec2
Get the center point of view.
// add bean to the center of the screen
add([
sprite("bean"),
pos(center()),
// ...
])
returns
The center point of the view.
since
v2000.0
group
Info
dt(): number
Get the delta time since last frame.
// rotate bean 100 deg per second
bean.onUpdate(() => {
bean.angle += 100 * dt()
})
since
v2000.0
group
Info
fixedDt(): number
Get the fixed delta time since last frame.
since
v3000.0
group
Info
restDt(): number
Get the rest delta time since last frame.
since
v3000.0
group
Info
time(): number
Get the total time since beginning.
since
v3001
group
Info
isFocused(): boolean
If the game canvas is currently focused.
returns
true if focused.
since
v2000.1
group
Info
setBackground(color: Color): void
Set background color.
since
v3000.0
group
Info
setBackground(color: Color, alpha: number): void
setBackground(r: number, g: number, b: number): void
setBackground(r: number, g: number, b: number, alpha: number): void
getBackground(): Color | null
Get background color.
returns
The background color.
since
v3000.0
group
Info
getGamepads(): KGamepad[]
Get connected gamepads.
returns
An array of connected gamepads.
since
v3000.0
group
Info
setCursor(style: Cursor): void
Set cursor style.
param
style- The cursor style.
// Change between cursor styles
// Reset cursor to default at start of every frame
onUpdate(() => setCursor("default"));
button.onHover((c) => {
// change cursor to pointer when hovering over button
setCursor("pointer")
})
// Hide the only cursor at start (useful for fakeMouse)
setCursor("none");
since
v2000.0
group
Info
getCursor(): Cursor
Get current cursor style.
returns
The current cursor style.
since
v2000.0
group
Info
setCursorLocked(locked: boolean): void
Lock / unlock cursor. Note that you cannot lock cursor within 1 second after user unlocking the cursor with the default unlock gesture (typically the esc key) due to browser policy.
since
v2000.0
group
Info
isCursorLocked(): boolean
Get if cursor is currently locked.
returns
true if locked, false otherwise.
since
v2000.0
group
Info
setFullscreen(f?: boolean): void
Enter / exit fullscreen mode. (note: mouse position is not working in fullscreen mode at the moment)
// toggle fullscreen mode on "f"
onKeyPress("f", (c) => {
setFullscreen(!isFullscreen());
});
since
v2000.0
group
Info
isFullscreen(): boolean
If currently in fullscreen mode.
returns
true if fullscreen, false otherwise.
since
v2000.0
group
Info
canvas: HTMLCanvasElement
The canvas DOM KAPLAY is currently using.
since
v2000.0
group
Info
VERSION: string
Current KAPLAY library version.
since
v3000.0
group
Info
wait(n: number, action?: ()=>void): TimerController
Run the function after n seconds.
param
n- The time to wait in seconds.
param
action- The function to run.
// 3 seconds until explosion! Runnn!
wait(3, () => {
explode()
})
// wait() returns a PromiseLike that can be used with await
await wait(1)
returns
A timer controller.
since
v2000.0
group
Timer
loop(t: number, action: ()=>void, maxLoops?: number, waitFirst?: boolean): TimerController
Run the function every n seconds.
param
t- The time to wait in seconds.
param
action- The function to run.
param
maxLoops- The maximum number of loops to run. If not provided, it will run forever.
param
waitFirst- Whether to wait for the first loop to start.
// spawn a butterfly at random position every 1 second
loop(1, () => {
add([
sprite("butterfly"),
pos(rand(vec2(width(), height()))),
area(),
"friend",
])
})
returns
A timer controller.
since
v2000.0
group
Timer
TimerController: paused: boolean
If the event handler is paused.
cancel(): void
Cancel the event handler.
onEnd(action: ()=>void): void
Register an event when finished.
then(action: ()=>void): TimerController
group
Timer
TweenController: TimerController & finish(): void
Finish the tween now and cancel.
Event controller for tween.
group
Timer
Color:
0-255 RGBA color.
group
Math
r: number
Red (0-255.
g: number
Green (0-255).
b: number
Blue (0-255).
fromArray(arr: number[]): Color
fromHex(hex: string | number): Color
Create color from hex string or literal.
Color.fromHex(0xfcef8d)
Color.fromHex("#5ba675")
Color.fromHex("d46eb3")
since
v3000.0
fromHSL(h: number, s: number, l: number): Color
RED: Color
GREEN: Color
BLUE: Color
YELLOW: Color
MAGENTA: Color
CYAN: Color
WHITE: Color
BLACK: Color
clone(): Color
lighten(a: number): Color
Lighten the color (adds RGB by n).
darken(a: number): Color
Darkens the color (subtracts RGB by n).
invert(): Color
mult(other: Color): Color
lerp(dest: Color, t: number): Color
Linear interpolate to a destination color.
since
v3000.0
toHSL():
[
number, number, number
]
Convert color into HSL format.
since
v3001.0
eq(other: Color): boolean
toHex(): string
Return the hex string of color.
since
v3000.0
toArray(): Array<number>
Return the color converted to an array.
since
v3001.0
Vec2Args:
[
number, number
]
|
[
number
]
|
[
Vec2
]
|
[
number | Vec2
]
|
[
]
Possible arguments for a Vec2.
group
Math
Vec2:
A 2D vector.
group
Math
x: number
The x coordinate
y: number
The y coordinate
fromAngle(deg: number): Vec2
Create a new Vec2 from an angle in degrees
fromArray(arr: Array): Vec2
Create a new Vec2 from an array
ZERO: Vec2
An empty vector. (0, 0)
ONE: Vec2
A vector with both components of 1. (1, 1)
LEFT: Vec2
A vector signaling to the left. (-1, 0)
RIGHT: Vec2
A vector signaling to the right. (1, 0)
UP: Vec2
A vector signaling up. (0, -1)
DOWN: Vec2
A vector signaling down. (0, 1)
clone(): Vec2
Clone the vector
add(args: Vec2Args): Vec2
Returns the addition with another vector.
sub(args: Vec2Args): Vec2
Returns the subtraction with another vector.
scale(args: Vec2Args): Vec2
Scale by another vector. or a single number
dist(args: Vec2Args): number
Get distance between another vector
sdist(args: Vec2Args): number
Get squared distance between another vector
sdist(v: Vec2, other: Vec2): number
Calculates the squared distance between the vectors
param
vThe vector
param
otherThe other vector
returns
The distance between the vectors
len(): number
Get length of the vector
since
v3000.0
slen(): number
Get squared length of the vector
since
v3000.0
unit(): Vec2
Get the unit vector (length of 1).
normal(): Vec2
Get the perpendicular vector.
reflect(normal: Vec2): Vec2
Get the reflection of a vector with a normal.
since
v3000.0
project(on: Vec2): Vec2
Get the projection of a vector onto another vector.
since
v3000.0
reject(on: Vec2): Vec2
Get the rejection of a vector onto another vector.
since
v3000.0
dot(p2: Vec2): number
Get the dot product with another vector.
dot(v: Vec2, other: Vec2): number
Get the dot product between 2 vectors.
since
v3000.0
cross(p2: Vec2): number
Get the cross product with another vector.
since
v3000.0
cross(v: Vec2, other: Vec2): number
Get the cross product between 2 vectors.
since
v3000.0
angle(args: Vec2Args): number
Get the angle of the vector in degrees.
angleBetween(args: Vec2Args): number
Get the angle between this vector and another vector.
since
v3000.0
lerp(dest: Vec2, t: number): Vec2
Linear interpolate to a destination vector (for positions).
slerp(dest: Vec2, t: number): Vec2
Spherical linear interpolate to a destination vector (for rotations).
since
v3000.0
isZero(): boolean
If the vector (x, y) is zero.
since
v3000.0
toFixed(n: number): Vec2
To n precision floating point.
transform(m: Mat4): Vec2
Multiply by a Mat4.
since
v3000.0
eq(other: Vec2): boolean
See if one vector is equal to another.
since
v3000.0
bbox(): Rect
Converts the vector to a Rect with the vector as the origin.
since
v3000.0.
toArray(): Array<number>
Converts the vector to an array.
since
v3001.0
Quad:
group
Math
x: number
y: number
w: number
h: number
scale(other: Quad): Quad
pos(): Vec2
clone(): Quad
eq(other: Quad): boolean
Mat4:
group
Math
m: number[]
translate(p: Vec2): Mat4
translate(p: Vec2): this
scale(s: Vec2): Mat4
scale(p: Vec2): this
rotateX(a: number): Mat4
rotateY(a: number): Mat4
rotateZ(a: number): Mat4
rotate(a: number): Mat4
mult(other: Mat4): Mat4
multVec2(p: Vec2): Vec2
getTranslation(): Vec2
getScale(): Vec2
getRotation(): number
getSkew(): Vec2
invert(): Mat4
clone(): Mat4
RNG:
group
Math
seed: number
gen(): number
genNumber(a: number, b: number): number
genVec2(a: Vec2, b: Vec2): Vec2
genColor(a: Color, b: Color): Color
genAny<T>(args:
[
]
|
[
T
]
|
[
T, T
]
): T
ShapeType: Point | Circle | Line | Rect | Polygon | Ellipse
group
Math
RaycastHit: fraction: number
normal: Vec2
point: Vec2
gridPos?: Vec2
object?: GameObj
group
Math
RaycastResult: RaycastHit | null
group
Math
Line:
group
Math
p1: Vec2
p2: Vec2
transform(m: Mat4): Line
bbox(): Rect
area(): number
clone(): Line
collides(shape: ShapeType | Vec2): boolean
contains(point: Vec2): boolean
raycast(origin: Vec2, direction: Vec2): RaycastResult
random(): Vec2
Rect:
group
Math
pos: Vec2
width: number
height: number
fromPoints(p1: Vec2, p2: Vec2): Rect
center(): Vec2
points():
[
Vec2, Vec2, Vec2, Vec2
]
transform(m: Mat4): Polygon
bbox(): Rect
area(): number
clone(): Rect
distToPoint(p: Vec2): number
sdistToPoint(p: Vec2): number
collides(shape: ShapeType | Vec2): boolean
contains(point: Vec2): boolean
raycast(origin: Vec2, direction: Vec2): RaycastResult
random(): Vec2
Circle:
group
Math
center: Vec2
radius: number
transform(tr: Mat4): Ellipse
bbox(): Rect
area(): number
clone(): Circle
collides(shape: ShapeType | Vec2): boolean
contains(point: Vec2): boolean
raycast(origin: Vec2, direction: Vec2): RaycastResult
random(): Vec2
Ellipse:
group
Math
center: Vec2
radiusX: number
radiusY: number
angle: number
fromMat2(tr: Mat2): Ellipse
toMat2(): Mat2
transform(tr: Mat4): Ellipse
bbox(): Rect
area(): number
clone(): Ellipse
collides(shape: ShapeType): boolean
contains(point: Vec2): boolean
raycast(origin: Vec2, direction: Vec2): RaycastResult
random(): Vec2
Polygon:
group
Math
pts: Vec2[]
transform(m: Mat4): Polygon
bbox(): Rect
area(): number
clone(): Polygon
collides(shape: ShapeType | Vec2): boolean
contains(point: Vec2): boolean
raycast(origin: Vec2, direction: Vec2): RaycastResult
random(): Vec2
cut(a: Vec2, b: Vec2):
[
Polygon | null, Polygon | null
]
UniformValue: number | Vec2 | Color | Mat4 | number[] | Vec2[] | Color[]
group
Math
UniformKey: Exclude<string, "u_tex">
group
Math
Uniform: Record<UniformKey, UniformValue>
group
Math
raycast(origin: Vec2, direction: Vec2, exclude?: string[]): RaycastResult
Create a raycast.
since
v3001.0
group
Math
vec2(x: number, y: number): Vec2
Create a 2D vector.
// { x: 0, y: 0 }
vec2()
// { x: 10, y: 10 }
vec2(10)
// { x: 100, y: 80 }
vec2(100, 80)
// move to 150 degrees direction with by length 10
player.pos = pos.add(Vec2.fromAngle(150).scale(10))
returns
The vector.
since
v2000.0
group
Math
vec2(p: Vec2): Vec2
vec2(xy: number): Vec2
vec2(): Vec2
rgb(r: number, g: number, b: number): Color
Create a color from RGB values (0 - 255).
param
r- The red value.
param
g- The green value.
param
b- The blue value.
// update the color of the sky to light blue
sky.color = rgb(0, 128, 255)
returns
The color.
since
v2000.0
group
Math
rgb(hex: string): Color
Create a color from hex string.
param
hex- The hex string.
sky.color = rgb("#ef6360")
returns
The color.
since
v2000.0
group
Math
rgb(): Color
Same as rgb(255, 255, 255).
group
Math
hsl2rgb(hue: number, saturation: number, lightness: number): Color
Convert HSL color (all values in 0.0 - 1.0 range) to RGB color.
param
hue- The hue value.
param
saturation- The saturation value.
param
lightness- The lightness value.
// animate rainbow color
onUpdate("rainbow", (obj) => {
obj.color = hsl2rgb(wave(0, 1, time()), 0.6, 0.6);
});
returns
The color.
since
v2000.1
group
Math
quad(x: number, y: number, w: number, h: number): Quad
Rectangle area (0.0 - 1.0).
param
x- The x position of the rectangle.
param
y- The y position of the rectangle.
param
w- The width of the rectangle.
param
h- The height of the rectangle.
returns
A Quad object.
since
v3001.0
group
Math
chance(p: number): boolean
rand(1) <= p
// every frame all objs with tag "unlucky" have 50% chance die
onUpdate("unlucky", (o) => {
if (chance(0.5)) {
destroy(o)
}
})
group
Math
lerp<V>(from: V, to: V, t: number): V
Linear interpolation.
group
Math
tween<V>(from: V, to: V, duration: number, setValue: (value: V)=>void, easeFunc?: (t: number)=>number): TweenController
Tweeeeeeeening!
since
v3000.0
// tween bean to mouse position
tween(bean.pos, mousePos(), 1, (p) => bean.pos = p, easings.easeOutBounce)
group
Math
easings: Record<EaseFuncs, EaseFunc>
A collection of easing functions for tweening.
since
v3000.0
group
Math
easingSteps(steps: number, position: StepPosition): number
Steps easing. Eases in discontinious steps.
since
v3001.0
group
Math
easingLinear(keys: Vec2[]): number
Linear easing with keyframes
since
v3001.0
group
Math
easingCubicBezier(p1: Vec2, p2: Vec2): number
Bezier easing. Both control points need x to be within 0 and 1.
since
v3001.0
group
Math
map(v: number, l1: number, h1: number, l2: number, h2: number): number
Map a value from one range to another range.
If the value overshoots, the source range, the result values will also do.
For clamping check mapc
param
vThe value the function will depend on.
param
l1The minimum value of the source range.
param
h1The minimum result value.
param
l2The maximum value of the source range.
param
h2The maximum result value.
onUpdate(() => {
// Redness will be 0 when the mouse is at the left edge and 255 when the mouse is at the right edge
const redness = map(mousePos().x, 0, width(), 0, 255)
setBackground(rgb(redness, 0, 0))
})
returns
The result value based on the source value.
since
v2000.0
group
Math
mapc(v: number, l1: number, h1: number, l2: number, h2: number): number
Map a value from one range to another range, and clamp to the dest range.
param
vThe value the function will depend on.
param
l1The minimum value of the source range.
param
h1The minimum result value.
param
l2The maximum value of the source range.
param
h2The maximum result value.
onUpdate(() => {
// This variable will be 0 when the mouse is at the left edge and 255 when the mouse is at the right edge
const redness = mapc(mousePos().x, 0, width(), 0, 255)
setBackground(rgb(redness, 0, 0))
})
returns
The clamped result value based on the source value.
since
v2000.0
group
Math
wave(lo: number, hi: number, t: number, func?: (x: number)=>number): number
Interpolate between 2 values (Optionally takes a custom periodic function, which default to Math.sin).
// bounce color between 2 values as time goes on
onUpdate("colorful", (c) => {
c.color.r = wave(0, 255, time())
c.color.g = wave(0, 255, time() + 1)
c.color.b = wave(0, 255, time() + 2)
})
group
Math
deg2rad(deg: number): number
Convert degrees to radians.
group
Math
rad2deg(rad: number): number
Convert radians to degrees.
group
Math
clamp(n: number, min: number, max: number): number
Return a value clamped to an inclusive range of min and max.
group
Math
evaluateQuadratic(pt1: Vec2, pt2: Vec2, pt3: Vec2, t: number): Vec2
Evaluate the quadratic Bezier at the given t
group
Math
evaluateQuadraticFirstDerivative(pt1: Vec2, pt2: Vec2, pt3: Vec2, t: number): Vec2
Evaluate the first derivative of a quadratic bezier at the given t
since
v3001.0
group
Math
evaluateQuadraticSecondDerivative(pt1: Vec2, pt2: Vec2, pt3: Vec2, t: number): Vec2
Evaluate the second derivative of a quadratic bezier at the given t
since
v3001.0
group
Math
evaluateBezier(pt1: Vec2, pt2: Vec2, pt3: Vec2, pt4: Vec2, t: number): Vec2
Evaluate the cubic Bezier at the given t
since
v3001.0
group
Math
evaluateBezierFirstDerivative(pt1: Vec2, pt2: Vec2, pt3: Vec2, pt4: Vec2, t: number): Vec2
Evaluate the first derivative of a cubic Bezier at the given t
group
Math
evaluateBezierSecondDerivative(pt1: Vec2, pt2: Vec2, pt3: Vec2, pt4: Vec2, t: number): Vec2
Evaluate the second derivative of a cubic bezier at the given t
since
v3001.0
group
Math
evaluateCatmullRom(pt1: Vec2, pt2: Vec2, pt3: Vec2, pt4: Vec2, t: number): Vec2
Evaluate the Catmull-Rom spline at the given t
since
v3001.0
group
Math
evaluateCatmullRomFirstDerivative(pt1: Vec2, pt2: Vec2, pt3: Vec2, pt4: Vec2, t: number): Vec2
Evaluate the first derivative of a Catmull-Rom spline at the given t
since
v3001.0
group
Math
curveLengthApproximation(curve: (t: number)=>Vec2, entries: number, detail: number): number
Returns a function.
entries is the amount of entries in the LUT.
detail is the sampling granularity of each segment recorded in the LUT.
This new function either returns the length for a given t, or t for a given length, depending on the inverse parameter.
since
v3001.0
group
Math
normalizedCurve(curve: (t: number)=>Vec2): Vec2
Returns a new curve which is normalized. This new curve has constant speed
curve is any curve in t (non-constant between 0 and 1)
returns a curve in s (constant between 0 and 1)
since
v3001.0
group
Math
testLinePoint(l: Line, pt: Vec2): boolean
Check if a line and a point intersect.
param
l- The line.
param
pt- The point.
returns
true if the line and point intersects.
since
v2000.0
group
Math
testLineLine(l1: Line, l2: Line): Vec2 | null
Check if 2 lines intersects, if yes returns the intersection point.
param
l1- The first line.
param
l2- The second line.
return
The intersection point, or null if the lines are parallel.
since
v2000.0
group
Math
testLineCircle(l: Line, c: Circle): boolean
Check if a line and a circle intersect.
param
l- The line.
param
c- The circle.
returns
true if the line and circle intersects.
since
v2000.0
group
Math
testRectRect(r1: Rect, r2: Rect): boolean
Check if 2 rectangle overlaps.
param
r1- The first rectangle.
param
r2- The second rectangle.
returns
true if the rectangles overlap.
since
v2000.0
group
Math
testRectLine(r: Rect, l: Line): boolean
Check if a line and a rectangle overlaps.
param
r- The line.
param
l- The rectangle.
returns
true if the line and rectangle overlaps.
since
v2000.0
group
Math
testRectPoint(r: Rect, pt: Vec2): boolean
Check if a point is inside a rectangle.
param
r- The rectangle.
param
pt- The point.
returns
true if the point is inside the rectangle.
since
v2000.0
group
Math
testCirclePolygon(c: Circle, p: Polygon): boolean
Check if a circle and polygon intersect linewise.
param
c- The circle.
param
p- The polygon.
returns
true if the circle and polygon intersect linewise.
since
v2000.0
group
Math
isConvex(pts: Vec2[]): boolean
group
Math
triangulate(pts: Vec2[]): Vec2[][]
since
v3001.0
group
Math
NavMesh:
_polygons:
_pointCache:
_edgeCache:
_addPoint:
_addEdge:
_findEdge:
_findCommonEdge:
addPolygon(vertices: Vec2[]): NavPolygon
addRect(pos: Vec2, size: Vec2): NavPolygon
_getLocation:
getNeighbours(index: number): number[]
getCost(a: number, b: number): number
getHeuristic(indexA: number, indexB: number): number
getPath(start: number, goal: number): number[]
getWaypointPath(start: Vec2, goal: Vec2, opt: any): Vec2[]
Point:
pt: Vec2
transform(m: Mat4): Point
bbox(): Rect
area(): number
clone(): Point
collides(shape: ShapeType): boolean
contains(point: Vec2): boolean
raycast(origin: Vec2, direction: Vec2): RaycastResult
random(): Vec2
Line:
group
Math
p1: Vec2
p2: Vec2
transform(m: Mat4): Line
bbox(): Rect
area(): number
clone(): Line
collides(shape: ShapeType | Vec2): boolean
contains(point: Vec2): boolean
raycast(origin: Vec2, direction: Vec2): RaycastResult
random(): Vec2
Rect:
group
Math
pos: Vec2
width: number
height: number
fromPoints(p1: Vec2, p2: Vec2): Rect
center(): Vec2
points():
[
Vec2, Vec2, Vec2, Vec2
]
transform(m: Mat4): Polygon
bbox(): Rect
area(): number
clone(): Rect
distToPoint(p: Vec2): number
sdistToPoint(p: Vec2): number
collides(shape: ShapeType | Vec2): boolean
contains(point: Vec2): boolean
raycast(origin: Vec2, direction: Vec2): RaycastResult
random(): Vec2
Circle:
group
Math
center: Vec2
radius: number
transform(tr: Mat4): Ellipse
bbox(): Rect
area(): number
clone(): Circle
collides(shape: ShapeType | Vec2): boolean
contains(point: Vec2): boolean
raycast(origin: Vec2, direction: Vec2): RaycastResult
random(): Vec2
Ellipse:
group
Math
center: Vec2
radiusX: number
radiusY: number
angle: number
fromMat2(tr: Mat2): Ellipse
toMat2(): Mat2
transform(tr: Mat4): Ellipse
bbox(): Rect
area(): number
clone(): Ellipse
collides(shape: ShapeType): boolean
contains(point: Vec2): boolean
raycast(origin: Vec2, direction: Vec2): RaycastResult
random(): Vec2
Polygon:
group
Math
pts: Vec2[]
transform(m: Mat4): Polygon
bbox(): Rect
area(): number
clone(): Polygon
collides(shape: ShapeType | Vec2): boolean
contains(point: Vec2): boolean
raycast(origin: Vec2, direction: Vec2): RaycastResult
random(): Vec2
cut(a: Vec2, b: Vec2):
[
Polygon | null, Polygon | null
]
Vec2:
A 2D vector.
group
Math
x: number
The x coordinate
y: number
The y coordinate
fromAngle(deg: number): Vec2
Create a new Vec2 from an angle in degrees
fromArray(arr: Array): Vec2
Create a new Vec2 from an array
ZERO: Vec2
An empty vector. (0, 0)
ONE: Vec2
A vector with both components of 1. (1, 1)
LEFT: Vec2
A vector signaling to the left. (-1, 0)
RIGHT: Vec2
A vector signaling to the right. (1, 0)
UP: Vec2
A vector signaling up. (0, -1)
DOWN: Vec2
A vector signaling down. (0, 1)
clone(): Vec2
Clone the vector
add(args: Vec2Args): Vec2
Returns the addition with another vector.
sub(args: Vec2Args): Vec2
Returns the subtraction with another vector.
scale(args: Vec2Args): Vec2
Scale by another vector. or a single number
dist(args: Vec2Args): number
Get distance between another vector
sdist(args: Vec2Args): number
Get squared distance between another vector
sdist(v: Vec2, other: Vec2): number
Calculates the squared distance between the vectors
param
vThe vector
param
otherThe other vector
returns
The distance between the vectors
len(): number
Get length of the vector
since
v3000.0
slen(): number
Get squared length of the vector
since
v3000.0
unit(): Vec2
Get the unit vector (length of 1).
normal(): Vec2
Get the perpendicular vector.
reflect(normal: Vec2): Vec2
Get the reflection of a vector with a normal.
since
v3000.0
project(on: Vec2): Vec2
Get the projection of a vector onto another vector.
since
v3000.0
reject(on: Vec2): Vec2
Get the rejection of a vector onto another vector.
since
v3000.0
dot(p2: Vec2): number
Get the dot product with another vector.
dot(v: Vec2, other: Vec2): number
Get the dot product between 2 vectors.
since
v3000.0
cross(p2: Vec2): number
Get the cross product with another vector.
since
v3000.0
cross(v: Vec2, other: Vec2): number
Get the cross product between 2 vectors.
since
v3000.0
angle(args: Vec2Args): number
Get the angle of the vector in degrees.
angleBetween(args: Vec2Args): number
Get the angle between this vector and another vector.
since
v3000.0
lerp(dest: Vec2, t: number): Vec2
Linear interpolate to a destination vector (for positions).
slerp(dest: Vec2, t: number): Vec2
Spherical linear interpolate to a destination vector (for rotations).
since
v3000.0
isZero(): boolean
If the vector (x, y) is zero.
since
v3000.0
toFixed(n: number): Vec2
To n precision floating point.
transform(m: Mat4): Vec2
Multiply by a Mat4.
since
v3000.0
eq(other: Vec2): boolean
See if one vector is equal to another.
since
v3000.0
bbox(): Rect
Converts the vector to a Rect with the vector as the origin.
since
v3000.0.
toArray(): Array<number>
Converts the vector to an array.
since
v3001.0
Color:
0-255 RGBA color.
group
Math
r: number
Red (0-255.
g: number
Green (0-255).
b: number
Blue (0-255).
fromArray(arr: number[]): Color
fromHex(hex: string | number): Color
Create color from hex string or literal.
Color.fromHex(0xfcef8d)
Color.fromHex("#5ba675")
Color.fromHex("d46eb3")
since
v3000.0
fromHSL(h: number, s: number, l: number): Color
RED: Color
GREEN: Color
BLUE: Color
YELLOW: Color
MAGENTA: Color
CYAN: Color
WHITE: Color
BLACK: Color
clone(): Color
lighten(a: number): Color
Lighten the color (adds RGB by n).
darken(a: number): Color
Darkens the color (subtracts RGB by n).
invert(): Color
mult(other: Color): Color
lerp(dest: Color, t: number): Color
Linear interpolate to a destination color.
since
v3000.0
toHSL():
[
number, number, number
]
Convert color into HSL format.
since
v3001.0
eq(other: Color): boolean
toHex(): string
Return the hex string of color.
since
v3000.0
toArray(): Array<number>
Return the color converted to an array.
since
v3001.0
Mat4:
group
Math
m: number[]
translate(p: Vec2): Mat4
translate(p: Vec2): this
scale(s: Vec2): Mat4
scale(p: Vec2): this
rotateX(a: number): Mat4
rotateY(a: number): Mat4
rotateZ(a: number): Mat4
rotate(a: number): Mat4
mult(other: Mat4): Mat4
multVec2(p: Vec2): Vec2
getTranslation(): Vec2
getScale(): Vec2
getRotation(): number
getSkew(): Vec2
invert(): Mat4
clone(): Mat4
Quad:
group
Math
x: number
y: number
w: number
h: number
scale(other: Quad): Quad
pos(): Vec2
clone(): Quad
eq(other: Quad): boolean
RNG:
group
Math
seed: number
gen(): number
genNumber(a: number, b: number): number
genVec2(a: Vec2, b: Vec2): Vec2
genColor(a: Color, b: Color): Color
genAny<T>(args:
[
]
|
[
T
]
|
[
T, T
]
): T
LerpValue: number | Vec2 | Color
group
Math
RNGValue: number | Vec2 | Color
group
Math
Collision:
Collision resolution data.
group
Math
source: GameObj
The first game object in the collision.
target: GameObj
The second game object in the collision.
normal: Vec2
The contact normal.
distance: Vec2
The length of the displacement.
displacement: Vec2
The displacement source game object have to make to avoid the collision.
resolved: boolean
If the collision is resolved.
preventResolution(): void
Prevent collision resolution if not yet resolved.
since
v3000.0
hasOverlap(): boolean
If the 2 objects have any overlap, or they're just touching edges.
since
v3000.0
reverse(): Collision
Get a new collision with reversed source and target relationship.
isTop(): boolean
If the collision happened (roughly) on the top side.
isBottom(): boolean
If the collision happened (roughly) on the bottom side.
isLeft(): boolean
If the collision happened (roughly) on the left side.
isRight(): boolean
If the collision happened (roughly) on the right side.
Edge: "left" | "right" | "top" | "bottom"
group
Math
EaseFuncs: "linear" | "easeInSine" | "easeOutSine" | "easeInOutSine" | "easeInQuad" | "easeOutQuad" | "easeInOutQuad" | "easeInCubic" | "easeOutCubic" | "easeInOutCubic" | "easeInQuart" | "easeOutQuart" | "easeInOutQuart" | "easeInQuint" | "easeOutQuint" | "easeInOutQuint" | "easeInExpo" | "easeOutExpo" | "easeInOutExpo" | "easeInCirc" | "easeOutCirc" | "easeInOutCirc" | "easeInBack" | "easeOutBack" | "easeInOutBack" | "easeInElastic" | "easeOutElastic" | "easeInOutElastic" | "easeInBounce" | "easeOutBounce" | "easeInOutBounce"
The list of easing functions available.
group
Math
EaseFunc(t: number): number
A function that takes a time value and returns a new time value.
group
Math
GfxCtx: ReturnType<initGfx>
Texture:
ctx: GfxCtx
src: null | ImageSource
glTex: WebGLTexture
width: number
height: number
fromImage(ctx: GfxCtx, img: ImageSource, opt?: TextureOpt): Texture
update(img: ImageSource, x?: number, y?: number): void
bind(): void
unbind(): void
free(): void
Frees up texture memory. Call this once the texture is no longer being used to avoid memory leaks.
VertexFormat: size: number
[]
BatchRenderer:
ctx: GfxCtx
glVBuf: WebGLBuffer
glIBuf: WebGLBuffer
vqueue: number[]
iqueue: number[]
stride: number
maxVertices: number
maxIndices: number
vertexFormat: VertexFormat
numDraws: number
curPrimitive: GLenum | null
curTex: Texture | null
curShader: Shader | null
curUniform: Uniform
push(primitive: GLenum, verts: number[], indices: number[], shader: Shader, tex?: Texture | null, uniform?: Uniform): void
flush(): void
free(): void
Mesh:
ctx: GfxCtx
glVBuf: WebGLBuffer
glIBuf: WebGLBuffer
vertexFormat: VertexFormat
count: number
draw(primitive?: GLenum): void
free(): void
initGfx(gl: WebGLRenderingContext, opts?: texFilter?: TexFilter
): gl: WebGLRenderingContext
opts: texFilter?: TexFilter
onDestroy(action: ()=>unknown): void
destroy(): void
pushTexture2D(item: WebGLTexture): void
popTexture2D(): void
pushArrayBuffer(item: WebGLBuffer): void
popArrayBuffer(): void
pushElementArrayBuffer(item: WebGLBuffer): void
popElementArrayBuffer(): void
pushFramebuffer(item: WebGLFramebuffer): void
popFramebuffer(): void
pushRenderbuffer(item: WebGLRenderbuffer): void
popRenderbuffer(): void
pushViewport(item: x: number
y: number
w: number
h: number
): void
popViewport(): void
pushProgram(item: WebGLProgram): void
popProgram(): void
setVertexFormat(fmt: VertexFormat): void
RGBValue:
[
number, number, number
]
RGBAValue:
[
number, number, number, number
]
ColorArgs:
[
Color
]
|
[
Color, number
]
| RGBValue | RGBAValue |
[
string
]
|
[
number[]
]
|
[
]
Mat2:
a: number
b: number
c: number
d: number
mul(other: Mat2): Mat2
transform(point: Vec2): Vec2
inverse(): Mat2
transpose(): Mat2
eigenvalues(): number[]
eigenvectors(e1: number, e2: number): number[][]
det(): number
trace(): number
rotation(radians: number): Mat2
scale(x: number, y: number): Mat2
Point:
pt: Vec2
transform(m: Mat4): Point
bbox(): Rect
area(): number
clone(): Point
collides(shape: ShapeType): boolean
contains(point: Vec2): boolean
raycast(origin: Vec2, direction: Vec2): RaycastResult
random(): Vec2
StepPosition: "jump-start" | "jump-end" | "jump-none" | "jump-both"
SatResult: normal: Vec2
distance: number
DrawCurveOpt: RenderProps & segments?: number
The amount of line segments to draw.
width?: number
The width of the line.
DrawBezierOpt: DrawCurveOpt & pt1: Vec2
The first point.
pt2: Vec2
The the first control point.
pt3: Vec2
The the second control point.
pt4: Vec2
The second point.
DrawCircleOpt: Omit & radius: number
Radius of the circle.
start?: number
Starting angle.
fill?: boolean
If fill the shape with color (set this to false if you only want an outline).
gradient?:
[
Color, Color
]
Use gradient instead of solid color.
since
v3000.0
resolution?: number
Multiplier for circle vertices resolution (default 1)
anchor?: Anchor | Vec2
The anchor point, or the pivot point. Default to "topleft".
How the circle should look like.
GfxFont:
tex: Texture
map: Record<string, Quad>
size: number
BitmapFontData: GfxFont
LoadBitmapFontOpt:
chars?: string
filter?: TexFilter
outline?: number
FontData:
fontface: FontFace
filter: TexFilter
outline: Outline | null
size: number
CharTransformFunc(idx: number, ch: string): CharTransform
A function that returns a character transform config. Useful if you're generating dynamic styles.
FormattedText: width: number
height: number
chars: FormattedChar[]
opt: DrawTextOpt
renderedText: string
Formatted text with info on how and where to render each character.
FormattedChar:
One formated character.
ch: string
tex: Texture
width: number
height: number
quad: Quad
pos: Vec2
scale: Vec2
angle: number
color: Color
opacity: number
DrawLineOpt: Omit & p1: Vec2
Starting point of the line.
p2: Vec2
Ending point of the line.
width?: number
The width, or thickness of the line,
How the line should look like.
LineJoin: "none" | "round" | "bevel" | "miter"
LineCap: "butt" | "round" | "square"
DrawLinesOpt: Omit & pts: Vec2[]
The points that should be connected with a line.
width?: number
The width, or thickness of the lines,
radius?: number | number[]
The radius of each corner.
join?: LineJoin
Line join style (default "none").
cap?: LineCap
Line cap style (default "none").
miterLimit?: number
Maximum miter length, anything longer becomes bevel.
How the lines should look like.
DrawRectOpt: RenderProps & width: number
Width of the rectangle.
height: number
Height of the rectangle.
gradient?:
[
Color, Color
]
Use gradient instead of solid color.
since
v3000.0
horizontal?: boolean
If the gradient should be horizontal.
since
v3000.0
fill?: boolean
If fill the shape with color (set this to false if you only want an outline).
radius?: number | number[]
The radius of each corner.
anchor?: Anchor | Vec2
The anchor point, or the pivot point. Default to "topleft".
How the rectangle should look like.
Graph:
getNeighbours(node: number): number[]
getCost(node: number, neighbor: number): number
getHeuristic(node: number, goal: number): number
getPath(from: number, to: number): number[]
getWaypointPath(from: Vec2, to: Vec2, opt: any): Vec2[]
Grid:
A grid is a graph consisting of connected grid cells
_columns:
_rows:
_tileWidth:
_tileHeight:
_data:
_diagonals:
_connMap:
_buildConnectivityMap:
_getTile:
_getTileX:
_getTileY:
getNeighbours(tile: number): number[]
getCost(a: number, b: number): number
getHeuristic(a: number, b: number): number
getPath(start: number, goal: number): number[]
getWaypointPath(start: Vec2, goal: Vec2): Vec2[]
NavEdge:
a: Vec2
b: Vec2
polygon: WeakRef<NavPolygon>
isLeft(x: number, y: number): number
middle(): Vec2
NavPolygon:
_edges:
_centroid:
_id:
id(): number
edges(edges: NavEdge[]):
edges(): NavEdge[]
centroid(): Vec2
contains(p: Vec2): boolean
NavMesh:
_polygons:
_pointCache:
_edgeCache:
_addPoint:
_addEdge:
_findEdge:
_findCommonEdge:
addPolygon(vertices: Vec2[]): NavPolygon
addRect(pos: Vec2, size: Vec2): NavPolygon
_getLocation:
getNeighbours(index: number): number[]
getCost(a: number, b: number): number
getHeuristic(indexA: number, indexB: number): number
getPath(start: number, goal: number): number[]
getWaypointPath(start: Vec2, goal: Vec2, opt: any): Vec2[]
DrawSpriteOpt: RenderProps & sprite: string | SpriteData | Asset
The sprite name in the asset manager, or the raw sprite data.
frame?: number
If the sprite is loaded with multiple frames, or sliced, use the frame option to specify which frame to draw.
width?: number
Width of sprite. If `height` is not specified it'll stretch with aspect ratio. If `tiled` is set to true it'll tiled to the specified width horizontally.
height?: number
Height of sprite. If `width` is not specified it'll stretch with aspect ratio. If `tiled` is set to true it'll tiled to the specified width vertically.
tiled?: boolean
When set to true, `width` and `height` will not scale the sprite but instead render multiple tiled copies of them until the specified width and height. Useful for background texture pattern etc.
flipX?: boolean
If flip the texture horizontally.
flipY?: boolean
If flip the texture vertically.
quad?: Quad
The sub-area to render from the texture, by default it'll render the whole `quad(0, 0, 1, 1)`
anchor?: Anchor | Vec2
The anchor point, or the pivot point. Default to "topleft".
pos?: Vec2
The position
How the sprite should look like.
DrawTriangleOpt: RenderProps & p1: Vec2
First point of triangle.
p2: Vec2
Second point of triangle.
p3: Vec2
Third point of triangle.
fill?: boolean
If fill the shape with color (set this to false if you only want an outline).
radius?: number
The radius of each corner.
How the triangle should look like.
ShaderData: Shader
AppGfxCtx: ReturnType<initAppGfx>
TexPacker:
lastTextureId:
textures:
bigTextures:
texturesPosition:
canvas:
c2d:
x:
y:
curHeight:
gfx:
padding:
addSingle(img: ImageSource):
[
Texture, Quad, number
]
add(img: ImageSource):
[
Texture, Quad, number
]
free(): void
SoundData:
buf: AudioBuffer
fromArrayBuffer(buf: ArrayBuffer): Promise<SoundData>
fromURL(url: string): Promise<SoundData>
SpriteAnim: number | from?: number
The starting frame.
to?: number
The end frame.
loop?: boolean
If this anim should be played in loop.
pingpong?: boolean
When looping should it move back instead of go to start frame again.
speed?: number
This anim's speed in frames per second.
frames?: number[]
List of frames for the animation.
If this property exists, **from, to, and pingpong will be ignored**.
Frame-based animation configuration.
SpriteAnims: Record<string, SpriteAnim>
A dict of name <-> animation.
LoadSpriteOpt:
Sprite loading configuration.
sliceX?: number
If the defined area contains multiple sprites, how many frames are in the area horizontally.
sliceY?: number
If the defined area contains multiple sprites, how many frames are in the area vertically.
slice9?: NineSlice
9 slice sprite for proportional scaling.
since
v3000.0
frames?: Quad[]
Individual frames.
since
v3000.0
anims?: SpriteAnims
Animation configuration.
singular?: boolean
If the sprite is a single image.
NineSlice: left: number
The width of the 9-slice's left column.
right: number
The width of the 9-slice's right column.
top: number
The height of the 9-slice's top row.
bottom: number
The height of the 9-slice's bottom row.
LoadSpriteSrc: string | ImageSource
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>
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): this
onError(action: (err: Error)=>void): this
onFinish(action: ()=>void): this
then(action: (data: D)=>void): Asset<D>
catch(action: (err: Error)=>void): Asset<D>
finally(action: ()=>void): Asset<D>
AssetBucket<D>:
assets: Map<string, Asset>
lastUID: number
add(name: string | null, loader: Promise): Asset<D>
addLoaded(name: string | null, data: D): Asset<D>
get(handle: string): Asset | undefined
progress(): number
getFailedAssets():
[
string, Asset
]
[]
AssetsCtx: ReturnType<initAssets>
AsepriteData: frames: Array< frame: x: number
y: number
w: number
h: number
>
meta: size: w: number
h: number
frameTags: Array< from: number
to: number
direction: "forward" | "reverse" | "pingpong"
>
PeditFile:
width: number
height: number
frames: string[]
anims: SpriteAnims
SpriteAtlasData: Record<string, SpriteAtlasEntry>
SpriteAtlasEntry: LoadSpriteOpt & x: number
X position of the top left corner.
y: number
Y position of the top left corner.
width: number
Sprite area width.
height: number
Sprite area height.
A sprite in a sprite atlas.
AudioCtx: ReturnType<initAudio>
Registry<T>:
lastID:
push(v: T): number
pushd(v: T): void
KEvent<Args>:
cancellers:
handlers:
add(action: (args: Args)=>unknown): KEventController
addOnce(action: (args: Args | PromiseLike[])=>void): KEventController
next(): Promise<Args>
trigger(args: Args): void
numListeners(): number
clear(): void
KEventHandler<EventMap>:
handlers:
registers: Partial<MappedType>
on<Name>(name: Name, action: (args: EventMap[Name])=>void): KEventController
onOnce<Name>(name: Name, action: (args: EventMap[Name])=>void): KEventController
next<Name>(name: Name): Promise<unknown>
trigger<Name>(name: Name, args: EventMap[Name]): void
remove<Name>(name: Name): void
clear(): void
numListeners<Name>(name: Name): number
BinaryHeap<T>:
_items: T[]
_compareFn(a: T, b: T): boolean
insert(item: T): void
Insert an item into the binary heap
remove(): T | null
Remove the smallest item from the binary heap in case of a min heap
or the greatest item from the binary heap in case of a max heap
clear(): void
Remove all items
moveUp(pos: number): void
moveDown(pos: number): void
swap(index1: number, index2: number): void
length(): number
Returns the amount of items
AudioPlayOpt:
Audio play configurations.
paused?: boolean
If audio should start out paused.
since
v3000.0
loop?: boolean
If audio should be played again from start when its ended.
volume?: number
Volume of audio. 1.0 means full volume, 0.5 means half volume.
speed?: number
Playback speed. 1.0 means normal playback speed, 2.0 means twice as fast.
detune?: number
Detune the sound. Every 100 means a semitone.
// play a random note in the octave
play("noteC", {
detune: randi(0, 12) * 100,
})
seek?: number
The start time, in seconds.
pan?: number
The stereo pan of the sound.
-1.0 means fully from the left channel, 0.0 means centered, 1.0 means fully right.
Defaults to 0.0.
AudioPlay:
play(time?: number): void
Start playing audio.
since
v3000.0
seek(time: number): void
Seek time.
since
v3000.0
stop(): void
Stop the sound.
since
v3001.0
paused: boolean
If the sound is paused.
since
v2000.1
speed: number
Playback speed of the sound. 1.0 means normal playback speed, 2.0 means twice as fast.
detune: number
Detune the sound. Every 100 means a semitone.
// tune down a semitone
music.detune = -100
// tune up an octave
music.detune = 1200
volume: number
Volume of the sound. 1.0 means full volume, 0.5 means half volume.
pan?: number
The stereo pan of the sound.
-1.0 means fully from the left channel, 0.0 means centered, 1.0 means fully right.
Defaults to 0.0.
loop: boolean
If the audio should start again when it ends.
time(): number
The current playing time (not accurate if speed is changed).
duration(): number
The total duration.
onEnd(action: ()=>void): KEventController
Register an event that runs when audio ends.
since
v3000.0
then(action: ()=>void): KEventController
EmitterOpt: shape?: ShapeType
lifetime?: number
rate?: number
direction: number
spread: number
Options for the particles's component
PathfinderMapComp:
navigate(origin: Vec2, target: Vec2, navigationOpt: any): Vec2[] | undefined
graph: Graph | undefined
PathfinderMapCompOpt:
graph?: Graph
PathfinderComp:
navigateTo(target: Vec2): Vec2[] | undefined
graph: Graph | undefined
PathfinderCompOpt:
graph?: Graph
navigationOpt?: any
PatrolComp:
waypoints: Vec2[] | undefined
patrolSpeed: number
nextLocation: Vec2 | undefined
onPatrolFinished(cb: (objects: GameObj[])=>void): KEventController
Attaches an event handler which is called when using "stop" and the end of the path is reached.
param
cbThe event handler called when the patrol finishes.
PatrolEndBehavior: "loop" | "ping-pong" | "stop"
PatrolCompOpt:
waypoints?: Vec2[]
speed?: number
endBehavior?: PatrolEndBehavior
SentryCandidatesCb(): GameObj[]
SentryCandidates: SentryCandidatesCb | QueryOpt
TimeDirection: "forward" | "reverse" | "ping-pong"
Interpolation: "none" | "linear" | "slerp" | "spline"
AnimateOpt:
duration: number
Duration of the animation in seconds
loops?: number
Loops, Default is undefined aka infinite
direction?: TimeDirection
Behavior when reaching the end of the animation. Default is forward.
easing?: EaseFunc
Easing function. Default is linear time.
interpolation?: Interpolation
Interpolation function. Default is linear interpolation.
timing?: number[]
Timestamps in percent for the given keys, if omitted, keys are equally spaced.
easings?: EaseFunc[]
Easings for the given keys, if omitted, easing is used.
AnimateCompOpt:
followMotion?: boolean
Changes the angle so it follows the motion, requires the rotate component
relative?: boolean
The animation is added to the base values of pos, angle, scale and opacity instead of replacing them
BaseValues:
pos: Vec2
angle: number
scale: Vec2
opacity: number
AnimateComp:
animate<T>(name: string, keys: T[], opts: AnimateOpt): void
Animates a property on this object.
param
nameName of the property to animate.
param
keysKeys determining the value at a certain point in time.
param
optsOptions.
unanimate(name: string): void
Removes the animation from the given property.
param
nameName of the property to remove the animation from.
unanimateAll(): void
Removes the animations from all properties
onAnimateFinished(cb: ()=>void): KEventController
Attaches an event handler which is called when all the animation channels have finished.
param
cbThe event handler called when the animation finishes.
onAnimateChannelFinished(cb: (name: string)=>void): KEventController
Attaches an event handler which is called when an animation channels has finished.
param
cbThe event handler called when an animation channel finishes.
base: BaseValues
Base values for relative animation
animation: paused: boolean
Pauses playing
seek(time: number): void
Move the animation to a specific point in time
duration: number
Returns the duration of the animation
serializeAnimationChannels(): Record<string, AnimationChannel>
serializeAnimationOptions(): followMotion?: boolean
relative?: boolean
Serializes the options of this object to plain Javascript types
AnimationChannelKeys: number[] | number[][]
AnimationOptions: duration: number
loops?: number
direction?: TimeDirection
easing?: string
interpolation?: Interpolation
timing?: number[]
easings?: string[]
AnimationChannel: keys: AnimationChannelKeys
& AnimationOptions
SurfaceEffectorCompOpt: speed: number
speedVariation?: number
forceScale?: number
SurfaceEffectorComp:
speed: number
speedVariation: number
forceScale: number
AreaEffectorCompOpt: useGlobalAngle?: boolean
forceAngle: number
forceMagnitude: number
forceVariation?: number
linearDrag?: number
AreaEffectorComp:
useGlobalAngle: boolean
forceAngle: number
forceMagnitude: number
forceVariation: number
linearDrag?: number
ForceMode: "constant" | "inverseLinear" | "inverseSquared"
PointEffectorCompOpt: forceMagnitude: number
forceVariation: number
distanceScale?: number
forceMode?: ForceMode
linearDrag?: number
PointEffectorComp:
forceMagnitude: number
forceVariation: number
distanceScale: number
forceMode: ForceMode
linearDrag: number
ConstantForceCompOpt: force?: Vec2
ConstantForceComp:
force?: Vec2
PlatformEffectorCompOpt: surfaceArc?: number
useOneWay?: boolean
PlatformEffectorComp:
surfaceArc: number
useOneWay: boolean
BuoyancyEffectorCompOpt: surfaceLevel: number
density?: number
linearDrag?: number
angularDrag?: number
flowAngle?: number
flowMagnitude?: number
flowVariation?: number
BuoyancyEffectorComp:
surfaceLevel: number
density: number
linearDrag: number
angularDrag: number
flowAngle: number
flowMagnitude: number
flowVariation: number
applyBuoyancy(body: GameObj, submergedArea: Polygon): void
applyDrag(body: GameObj, submergedArea: Polygon): void
GameObjEvents: GameObjEventMap & {}
GameObjEventNames: GameObjEventMap
AppEventMap: mouseMove:
[
]
mouseDown:
[
MouseButton
]
mousePress:
[
MouseButton
]
mouseRelease:
[
MouseButton
]
charInput:
[
string
]
keyPress:
[
Key
]
keyDown:
[
Key
]
keyPressRepeat:
[
Key
]
keyRelease:
[
Key
]
touchStart:
[
Vec2, Touch
]
touchMove:
[
Vec2, Touch
]
touchEnd:
[
Vec2, Touch
]
gamepadButtonDown:
[
KGamepadButton, KGamepad
]
gamepadButtonPress:
[
KGamepadButton, KGamepad
]
gamepadButtonRelease:
[
KGamepadButton, KGamepad
]
gamepadStick:
[
string, Vec2, KGamepad
]
gamepadConnect:
[
KGamepad
]
gamepadDisconnect:
[
KGamepad
]
buttonDown:
[
string
]
buttonPress:
[
string
]
buttonRelease:
[
string
]
scroll:
[
Vec2
]
hide:
[
]
show:
[
]
resize:
[
]
input:
[
]
App events with their arguments
TupleWithoutFirst<T>: ConditionalType
SceneName: string
The name of a scene.
SceneDef(args: any): void
Game: ReturnType<initGame>
KAPLAYInternal: k: KAPLAYCtx
globalOpt: KAPLAYOpt
gfx: AppGfxCtx
game: Game
app: App
assets: ReturnType<initAssets>
fontCacheCanvas: HTMLCanvasElement | null
fontCacheC2d: CanvasRenderingContext2D | null
debug: Debug
audio: AudioCtx
pixelDensity: number
canvas: HTMLCanvasElement
gscale: number
kaSprite: Asset<SpriteData>
boomSprite: Asset<SpriteData>
Sensitive KAPLAY data
_k: KAPLAYInternal
Internal data that should not be accessed directly.
readonly
group
Misc
addKaboom(pos: Vec2, opt?: BoomOpt): GameObj
Add an explosion effect.
param
pos- The position of the explosion.
param
opt- The options for the explosion.
onMousePress(() => {
addKaboom(mousePos());
});
returns
The explosion object.
since
v2000.0
group
Misc
Tag: string
UnionToIntersection<U>: ConditionalType
Defined<T>: ConditionalType
Expand<T>: ConditionalType
MergeObj<T>: Expand<UnionToIntersection>
MergePlugins<T>: MergeObj<ReturnType>
PluginList<T>: Array<T | KAPLAYPlugin>
GamepadDef: buttons: Record<string, KGamepadButton>
sticks: Partial<Record>
A gamepad definition.
KGamepad: index: number
The order of the gamepad in the gamepad list.
isPressed(b: KGamepadButton): boolean
If certain button is pressed.
isDown(b: KGamepadButton): boolean
If certain button is held down.
isReleased(b: KGamepadButton): boolean
If certain button is released.
getStick(stick: GamepadStick): Vec2
Get the value of a stick.
A KAPLAY gamepad
GameObjInspect: Record<Tag, string | null>
Inspect info for a game object.
SpriteAnimPlayOpt:
Sprite animation configuration when playing.
loop?: boolean
If this anim should be played in loop.
pingpong?: boolean
When looping should it move back instead of go to start frame again.
speed?: number
This anim's speed in frames per second.
onEnd?(): void
Runs when this animation ends.
MusicData: string
LoadFontOpt:
filter?: TexFilter
outline?: number | Outline
size?: number
The size to load the font in (default 64).
since
v3001.0
TextureOpt: filter?: TexFilter
wrap?: TexWrap
ImageSource: Exclude<TexImageSource, VideoFrame>
Canvas: width: number
height: number
toImageData(): ImageData
toDataURL(): string
clear(): void
draw(action: ()=>void): void
free(): void
fb: FrameBuffer
Vertex:
pos: Vec2
uv: Vec2
color: Color
opacity: number
TexFilter: "nearest" | "linear"
Texture scaling filter. "nearest" is mainly for sharp pixelated scaling, "linear" means linear interpolation.
TexWrap: "repeat" | "clampToEdge"
RenderProps:
Common render properties.
pos?: Vec2
scale?: Vec2 | number
angle?: number
color?: Color
opacity?: number
fixed?: boolean
shader?: string | ShaderData | Asset | null
uniform?: Uniform | null
outline?: Outline
DrawTextureOpt: RenderProps & tex: Texture
width?: number
height?: number
tiled?: boolean
flipX?: boolean
flipY?: boolean
quad?: Quad
anchor?: Anchor | Vec2
DrawUVQuadOpt: RenderProps & width: number
Width of the UV quad.
height: number
Height of the UV quad.
flipX?: boolean
If flip the texture horizontally.
flipY?: boolean
If flip the texture vertically.
tex?: Texture
The texture to sample for this quad.
quad?: Quad
The texture sampling area.
anchor?: Anchor | Vec2
The anchor point, or the pivot point. Default to "topleft".
DrawEllipseOpt: RenderProps & radiusX: number
The horizontal radius.
radiusY: number
The vertical radius.
start?: number
Starting angle.
fill?: boolean
If fill the shape with color (set this to false if you only want an outline).
gradient?:
[
Color, Color
]
Use gradient instead of solid color.
since
v3000.0
resolution?: number
Multiplier for circle vertices resolution (default 1)
anchor?: Anchor | Vec2
The anchor point, or the pivot point. Default to "topleft".
How the ellipse should look like.
DrawPolygonOpt: RenderProps & pts: Vec2[]
The points that make up the polygon
fill?: boolean
If fill the shape with color (set this to false if you only want an outline).
indices?: number[]
Manual triangulation.
offset?: Vec2
The center point of transformation in relation to the position.
radius?: number | number[]
The radius of each corner.
colors?: Color[]
The color of each vertex.
since
v3000.0
uv?: Vec2[]
The uv of each vertex.
since
v3001.0
tex?: Texture
The texture if uv are supplied.
since
v3001.0
triangulate?: boolean
Triangulate concave polygons.
since
v3001.0
How the polygon should look like.
Outline:
width?: number
The width, or thickness of the line.
color?: Color
The color of the line.
opacity?: number
Opacity (overrides fill opacity).
since
v3001.0
join?: LineJoin
Line join.
since
v3000.0
miterLimit?: number
Miter limit. If the length of the miter divided by the line width exceeds this limit, the style is converted to a bevel.
since
v3001.0
cap?: LineCap
Line cap.
since
v3001.0
Mask: "intersect" | "subtract"
EdgeMask:
None:
Left:
Top:
LeftTop:
Right:
Horizontal:
RightTop:
HorizontalTop:
Bottom:
LeftBottom:
Vertical:
LeftVertical:
RightBottom:
HorizontalBottom:
RightVertical:
All:
SpriteCurAnim:
timer: number
loop: boolean
speed: number
frameIndex: number
The current index relative to the start of the
associated `frames` array for this animation.
This may be greater than the number of frames
in the sprite.
pingpong: boolean
onEnd(): void
ButtonState<T>:
pressed: Set<T>
pressedRepeat: Set<T>
released: Set<T>
down: Set<T>
update(): void
press(btn: T): void
pressRepeat(btn: T): void
release(btn: T): void
GamepadState:
buttonState: ButtonState<KGamepadButton>
stickState: Map<GamepadStick, Vec2>
FPSCounter:
dts:
timer:
fps: number
tick(dt: number): void
App: ReturnType<initApp>
AppState: ReturnType<initAppState>
initAppGfx(gopt: KAPLAYOpt, ggl: GfxCtx): lastDrawCalls: number
ggl: gl: WebGLRenderingContext
opts: texFilter?: TexFilter
onDestroy(action: ()=>unknown): void
destroy(): void
pushTexture2D(item: WebGLTexture): void
popTexture2D(): void
pushArrayBuffer(item: WebGLBuffer): void
popArrayBuffer(): void
pushElementArrayBuffer(item: WebGLBuffer): void
popElementArrayBuffer(): void
pushFramebuffer(item: WebGLFramebuffer): void
popFramebuffer(): void
pushRenderbuffer(item: WebGLRenderbuffer): void
popRenderbuffer(): void
pushViewport(item: x: number
y: number
w: number
h: number
): void
popViewport(): void
pushProgram(item: WebGLProgram): void
popProgram(): void
setVertexFormat(fmt: VertexFormat): void
defShader: Shader
defTex: Texture
frameBuffer: FrameBuffer
postShader: string | null
postShaderUniform: Uniform | ()=>Uniform | null
renderer: BatchRenderer
transform: Mat4
transformStack: Mat4[]
bgTex: Texture
bgColor: Color | null
bgAlpha: number
width: number
height: number
viewport: x: number
y: number
width: number
height: number
scale: number
fixed: boolean
initAssets(ggl: GfxCtx, spriteAtlasPadding: number): urlPrefix: string
sprites: AssetBucket<SpriteData>
fonts: AssetBucket<FontData>
bitmapFonts: AssetBucket<GfxFont>
sounds: AssetBucket<SoundData>
shaders: AssetBucket<Shader>
custom: AssetBucket<any>
music: Record<string, string>
packer: TexPacker
loaded: boolean
initAudio(): ctx: AudioContext
masterNode: GainNode
burpSnd: SoundData
initGame(): events: KEventHandler< mouseMove:
[
]
mouseDown:
[
MouseButton
]
mousePress:
[
MouseButton
]
mouseRelease:
[
MouseButton
]
charInput:
[
string
]
keyPress:
[
Key
]
keyDown:
[
Key
]
keyPressRepeat:
[
Key
]
keyRelease:
[
Key
]
touchStart:
[
Vec2, Touch
]
touchMove:
[
Vec2, Touch
]
touchEnd:
[
Vec2, Touch
]
gamepadButtonDown:
[
string
]
gamepadButtonPress:
[
string
]
gamepadButtonRelease:
[
string
]
gamepadStick:
[
string, Vec2
]
gamepadConnect:
[
Gamepad
]
gamepadDisconnect:
[
Gamepad
]
scroll:
[
Vec2
]
add:
[
GameObj
]
destroy:
[
GameObj
]
use:
[
GameObj, string
]
unuse:
[
GameObj, string
]
tag:
[
GameObj, string
]
untag:
[
GameObj, string
]
load:
[
]
loadError:
[
string, Asset
]
loading:
[
number
]
error:
[
Error
]
input:
[
]
frameEnd:
[
]
resize:
[
]
sceneLeave:
[
string
]
sceneEnter:
[
string
]
>
objEvents: KEventHandler<GameObjEvents>
root: GameObj<TimerComp>
gravity: Vec2 | null
scenes: Record<SceneName, SceneDef>
currentScene: SceneName | null
layers: string[] | null
defaultLayerIndex: number
logs: msg: string | {}
time: number
[]
cam: pos: Vec2 | null
scale: Vec2
angle: number
shake: number
transform: Mat4
initAppState(opt: canvas: HTMLCanvasElement
touchToMouse?: boolean
gamepads?: Record<string, GamepadDef>
pixelDensity?: number
maxFPS?: number
buttons?: ButtonsDef
): canvas: HTMLCanvasElement
buttons: ButtonsDef
buttonsByKey: Map<Key, string[]>
buttonsByMouse: Map<MouseButton, string[]>
buttonsByGamepad: Map<KGamepadButton, string[]>
buttonsByKeyCode: Map<string, string[]>
loopID: null | number
stopped: boolean
dt: number
fixedDt: number
restDt: number
time: number
realTime: number
fpsCounter: FPSCounter
timeScale: number
skipTime: boolean
isHidden: boolean
numFrames: number
mousePos: Vec2
mouseDeltaPos: Vec2
keyState: ButtonState<Key>
mouseState: ButtonState<MouseButton>
mergedGamepadState: GamepadState
gamepadStates: Map<number, GamepadState>
lastInputDevice: "mouse" | "keyboard" | "gamepad" | null
buttonState: ButtonState<string>
gamepads: KGamepad[]
charInputted: string[]
isMouseMoved: boolean
lastWidth: number
lastHeight: number
events: KEventHandler<AppEventMap>
initApp(opt: canvas: HTMLCanvasElement
touchToMouse?: boolean
gamepads?: Record<string, GamepadDef>
pixelDensity?: number
maxFPS?: number
buttons?: ButtonsDef
): state: canvas: HTMLCanvasElement
buttons: ButtonsDef
buttonsByKey: Map<Key, string[]>
buttonsByMouse: Map<MouseButton, string[]>
buttonsByGamepad: Map<KGamepadButton, string[]>
buttonsByKeyCode: Map<string, string[]>
loopID: null | number
stopped: boolean
dt: number
fixedDt: number
restDt: number
time: number
realTime: number
fpsCounter: FPSCounter
timeScale: number
skipTime: boolean
isHidden: boolean
numFrames: number
mousePos: Vec2
mouseDeltaPos: Vec2
keyState: ButtonState<Key>
mouseState: ButtonState<MouseButton>
mergedGamepadState: GamepadState
gamepadStates: Map<number, GamepadState>
lastInputDevice: "mouse" | "keyboard" | "gamepad" | null
buttonState: ButtonState<string>
gamepads: KGamepad[]
charInputted: string[]
isMouseMoved: boolean
lastWidth: number
lastHeight: number
events: KEventHandler<AppEventMap>
dt(): number
fixedDt(): number
restDt(): number
time(): number
run(fixedUpdate: ()=>void, update: (processInput: ()=>void, resetInput: ()=>void)=>void): void
canvas: HTMLCanvasElement
fps(): number
numFrames(): number
quit(): void
isHidden(): boolean
setFullscreen(f?: boolean): void
isFullscreen(): boolean
setCursor(c: Cursor): void
screenshot(): string
getGamepads(): KGamepad[]
getCursor(): Cursor
setCursorLocked(b: boolean): void
isCursorLocked(): boolean
isTouchscreen(): boolean
mousePos(): Vec2
mouseDeltaPos(): Vec2
isKeyDown(k?: Key | Key[]): boolean
isKeyPressed(k?: Key | Key[]): boolean
isKeyPressedRepeat(k?: Key | Key[]): boolean
isKeyReleased(k?: Key | Key[]): boolean
isMouseDown(m?: MouseButton): boolean
isMousePressed(m?: MouseButton): boolean
isMouseReleased(m?: MouseButton): boolean
isMouseMoved(): boolean
isGamepadButtonPressed(btn?: KGamepadButton | KGamepadButton[]): boolean
isGamepadButtonDown(btn?: KGamepadButton | KGamepadButton[]): boolean
isGamepadButtonReleased(btn?: KGamepadButton | KGamepadButton[]): boolean
getGamepadStick(stick: GamepadStick): Vec2
isButtonPressed(btn?: string | string[]): boolean
isButtonDown(btn?: string | string[]): boolean
isButtonReleased(btn?: string | string[]): boolean
setButton(btn: string, binding: ButtonBinding): void
getButton(btn: string): ButtonBinding
pressButton(btn: string): void
releaseButton(btn: string): void
charInputted(): string[]
onResize(action: ()=>void): KEventController
onKeyDown: (action: (key: Key)=>void)=>KEventController & (key: Key | Key[], action: (key: Key)=>void)=>KEventController
onKeyPress: (action: (key: Key)=>void)=>KEventController & (key: Key | Key[], action: (key: Key)=>void)=>KEventController
onKeyPressRepeat: (action: (key: Key)=>void)=>KEventController & (key: Key | Key[], action: (key: Key)=>void)=>KEventController
onKeyRelease: (action: (key: Key)=>void)=>KEventController & (key: Key | Key[], action: (key: Key)=>void)=>KEventController
onMouseDown: (action: (m: MouseButton)=>void)=>KEventController & (mouse: MouseButton | MouseButton[], action: (m: MouseButton)=>void)=>KEventController
onMousePress: (action: (m: MouseButton)=>void)=>KEventController & (mouse: MouseButton | MouseButton[], action: (m: MouseButton)=>void)=>KEventController
onMouseRelease: (action: (m: MouseButton)=>void)=>KEventController & (mouse: MouseButton | MouseButton[], action: (m: MouseButton)=>void)=>KEventController
onMouseMove(f: (pos: Vec2, dpos: Vec2)=>void): KEventController
onCharInput(action: (ch: string)=>void): KEventController
onTouchStart(f: (pos: Vec2, t: Touch)=>void): KEventController
onTouchMove(f: (pos: Vec2, t: Touch)=>void): KEventController
onTouchEnd(f: (pos: Vec2, t: Touch)=>void): KEventController
onScroll(action: (delta: Vec2)=>void): KEventController
onHide(action: ()=>void): KEventController
onShow(action: ()=>void): KEventController
onGamepadButtonDown: (action: (btn: KGamepadButton, gamepad: KGamepad)=>void)=>KEventController & (btn: KGamepadButton, action: (btn: KGamepadButton, gamepad: KGamepad)=>void)=>KEventController
onGamepadButtonPress: (action: (btn: KGamepadButton, gamepad: KGamepad)=>void)=>KEventController & (btn: KGamepadButton | KGamepadButton[], action: (btn: KGamepadButton, gamepad: KGamepad)=>void)=>KEventController
onGamepadButtonRelease: (action: (btn: KGamepadButton, gamepad: KGamepad)=>void)=>KEventController & (btn: KGamepadButton | KGamepadButton[], action: (btn: KGamepadButton, gamepad: KGamepad)=>void)=>KEventController
onGamepadStick(stick: GamepadStick, action: (value: Vec2, gp: KGamepad)=>void): KEventController
onGamepadConnect(action: (gamepad: KGamepad)=>void): void
onGamepadDisconnect(action: (gamepad: KGamepad)=>void): void
onButtonPress: (action: (btn: string)=>void)=>KEventController & (btn: string | string, action: (btn: string)=>void)=>KEventController
onButtonDown: (action: (btn: string)=>void)=>KEventController & (btn: string | string, action: (btn: string)=>void)=>KEventController
onButtonRelease: (action: (btn: string)=>void)=>KEventController & (btn: string | string, action: (btn: string)=>void)=>KEventController
getLastInputDeviceType(): ButtonBindingDevice | null
events: KEventHandler<AppEventMap>
ButtonBinding: keyboard?: Key | Key[]
keyboardCode?: string | string[]
gamepad?: KGamepadButton | KGamepadButton[]
mouse?: MouseButton | MouseButton[]
A button binding.
group
Button Bindings
ButtonsDef: Record<string, ButtonBinding>
A buttons definition for an action (jump, walk-left, run).
group
Button Bindings
ButtonBindingDevice: "keyboard" | "gamepad" | "mouse"
A button binding device
group
Button Bindings
FrameBuffer:
group
GFX
ctx: GfxCtx
tex: Texture
glFramebuffer: WebGLFramebuffer
glRenderbuffer: WebGLRenderbuffer
width(): number
height(): number
toImageData(): ImageData
toDataURL(): string
clear(): void
draw(action: ()=>void): void
bind(): void
unbind(): void
free(): void
Shader:
group
GFX
ctx: GfxCtx
glProgram: WebGLProgram
bind(): void
unbind(): void
send(uniform: Uniform): void
free(): void
DrawTextOpt: RenderProps & text: string
The text to render.
font?: string | FontData | Asset | BitmapFontData | Asset
The name of font to use.
size?: number
The size of text (the height of each character).
align?: TextAlign
Text alignment (default "left")
since
v3000.0
width?: number
The maximum width. Will wrap word around if exceed.
lineSpacing?: number
The gap between each line (only available for bitmap fonts).
since
v2000.2
letterSpacing?: number
The gap between each character (only available for bitmap fonts).
since
v2000.2
anchor?: Anchor | Vec2
The anchor point, or the pivot point. Default to "topleft".
transform?: CharTransform | CharTransformFunc
Transform the pos, scale, rotation or color for each character based on the index or char (only available for bitmap fonts).
since
v2000.1
styles?: Record<string, CharTransform | CharTransformFunc>
Stylesheet for styled chunks, in the syntax of "this is a [stylename]styled[/stylename] word" (only available for bitmap fonts).
since
v2000.2
indentAll?: boolean
If true, any (whitespace) indent on the first line of the paragraph
will be copied to all of the lines for those parts that text-wrap.
How the text should look like.
group
Draw
TextAlign: "center" | "left" | "right"
How the text should be aligned.
group
Draw
drawSprite(opt: DrawSpriteOpt): void
Draw a sprite.
param
opt- The draw sprite options.
drawSprite({
sprite: "bean",
pos: vec2(100, 200),
frame: 3,
});
since
v2000.0
group
Draw
drawText(opt: DrawTextOpt): void
Draw a piece of text.
param
opt- The draw text options.
drawText({
text: "oh hi",
size: 48,
font: "sans-serif",
width: 120,
pos: vec2(100, 200),
color: rgb(0, 0, 255),
});
since
v2000.0
group
Draw
drawRect(opt: DrawRectOpt): void
Draw a rectangle.
param
opt- The draw rect options.
drawRect({
width: 120,
height: 240,
pos: vec2(20, 20),
color: YELLOW,
outline: { color: BLACK, width: 4 },
});
since
v2000.0
group
Draw
drawLine(opt: DrawLineOpt): void
Draw a line.
param
opt- The draw line options.
drawLine({
p1: vec2(0),
p2: mousePos(),
width: 4,
color: rgb(0, 0, 255),
});
since
v3000.0
group
Draw
drawLines(opt: DrawLinesOpt): void
Draw lines.
param
opt- The draw lines options.
drawLines({
pts: [ vec2(0), vec2(0, height()), mousePos() ],
width: 4,
pos: vec2(100, 200),
color: rgb(0, 0, 255),
});
since
v3000.0
group
Draw
drawCurve(curve: (t: number)=>Vec2, opt: DrawCurveOpt): void
Draw a curve.
drawCurve(t => evaluateBezier(a, b, c, d, t)
{
width: 2,
color: rgb(0, 0, 255),
});
since
v3001.0
group
Draw
drawBezier(opt: DrawBezierOpt): void
Draw a cubic Bezier curve.
param
opt- The draw cubic bezier options.
drawBezier({
pt1: vec2(100, 100),
pt2: vec2(200, 100),
pt3: vec2(200, 200),
pt4: vec2(100, 200),
width: 2,
color: GREEN
});
since
v3001.0
group
Draw
drawTriangle(opt: DrawTriangleOpt): void
Draw a triangle.
param
opt- The draw triangle options.
drawTriangle({
p1: vec2(0),
p2: vec2(0, height()),
p3: mousePos(),
pos: vec2(100, 200),
color: rgb(0, 0, 255),
});
since
v3001.0
group
Draw
drawCircle(opt: DrawCircleOpt): void
Draw a circle.
param
opt- The draw circle options.
drawCircle({
pos: vec2(100, 200),
radius: 120,
color: rgb(255, 255, 0),
});
since
v2000.0
group
Draw
drawEllipse(opt: DrawEllipseOpt): void
Draw an ellipse.
param
opt- The draw ellipse options.
drawEllipse({
pos: vec2(100, 200),
radiusX: 120,
radiusY: 120,
color: rgb(255, 255, 0),
});
since
v3000.0
group
Draw
drawPolygon(opt: DrawPolygonOpt): void
Draw a convex polygon from a list of vertices.
param
opt- The draw polygon options.
drawPolygon({
pts: [
vec2(-12),
vec2(0, 16),
vec2(12, 4),
vec2(0, -2),
vec2(-8),
],
pos: vec2(100, 200),
color: rgb(0, 0, 255),
});
since
v3000.0
group
Draw
drawUVQuad(opt: DrawUVQuadOpt): void
Draw a rectangle with UV data.
param
opt- The draw rect with UV options.
since
v2000.0
group
Draw
drawFormattedText(text: FormattedText): void
Draw a piece of formatted text from formatText().
param
text- The formatted text object.
// text background
const txt = formatText({
text: "oh hi",
});
drawRect({
width: txt.width,
height: txt.height,
});
drawFormattedText(txt);
since
v2000.2
group
Draw
drawMasked(content: ()=>void, mask: ()=>void): void
Whatever drawn in content will only be drawn if it's also drawn in mask (mask will not be rendered).
since
v3000.0
group
Draw
drawSubtracted(content: ()=>void, mask: ()=>void): void
Subtract whatever drawn in content by whatever drawn in mask (mask will not be rendered).
since
v3000.0
group
Draw
pushTransform(): void
Push current transform matrix to the transform stack.
pushTransform();
// These transforms will affect every render until popTransform()
pushTranslate(120, 200);
pushRotate(time() * 120);
pushScale(6);
drawSprite("bean");
drawCircle(vec2(0), 120);
// Restore the transformation stack to when last pushed
popTransform();
since
v2000.0
group
Draw
popTransform(): void
Pop the topmost transform matrix from the transform stack.
since
v2000.0
group
Draw
pushTranslate(x: number, y: number): void
Translate all subsequent draws.
pushTranslate(100, 100)
// this will be drawn at (120, 120)
drawText({
text: "oh hi",
pos: vec2(20, 20),
})
since
v2000.0
group
Draw
pushTranslate(p: Vec2): void
pushTranslate(args: Vec2Args |
[
undefined
]
): void
pushScale(x: number, y: number): void
Scale all subsequent draws.
since
v2000.0
group
Draw
pushScale(s: Vec2 | number): void
pushScale(args: Vec2Args |
[
undefined
]
|
[
undefined, undefined
]
): void
pushRotate(angle?: number): void
Rotate all subsequent draws.
since
v2000.0
group
Draw
pushMatrix(mat?: Mat4): void
Apply a transform matrix, ignore all prior transforms.
since
v3000.0
group
Draw
usePostEffect(name: string, uniform?: Uniform | ()=>Uniform): void
Apply a post process effect from a shader name.
loadShader("invert", null, `
vec4 frag(vec2 pos, vec2 uv, vec4 color, sampler2D tex) {
vec4 c = def_frag();
return vec4(1.0 - c.r, 1.0 - c.g, 1.0 - c.b, c.a);
}
`)
usePostEffect("invert")
since
v3000.0
group
Draw
formatText(options: DrawTextOpt): FormattedText
Format a piece of text without drawing (for getting dimensions, etc).
// text background
const txt = formatText({
text: "oh hi",
});
drawRect({
width: txt.width,
height: txt.height,
});
drawFormattedText(txt);
returns
The formatted text object.
since
v2000.2
group
Draw
makeCanvas(w: number, h: number): Canvas
Create a canvas to draw stuff offscreen.
returns
The canvas object.
since
v3001.0
group
Draw
Cursor: string | "auto" | "default" | "none" | "context-menu" | "help" | "pointer" | "progress" | "wait" | "cell" | "crosshair" | "text" | "vertical-text" | "alias" | "copy" | "move" | "no-drop" | "not-allowed" | "grab" | "grabbing" | "all-scroll" | "col-resize" | "row-resize" | "n-resize" | "e-resize" | "s-resize" | "w-resize" | "ne-resize" | "nw-resize" | "se-resize" | "sw-resize" | "ew-resize" | "ns-resize" | "nesw-resize" | "nwse-resize" | "zoom-int" | "zoom-out"
group
Draw
Anchor: "topleft" | "top" | "topright" | "left" | "center" | "right" | "botleft" | "bot" | "botright"
group
Draw
Shape: Rect | Line | Point | Circle | Ellipse | Polygon
group
Draw
CharTransform:
Describes how to transform each character.
group
Options
pos?: Vec2
Offset to apply to the position of the text character.
Shifts the character's position by the specified 2D vector.
scale?: Vec2 | number
Scale transformation to apply to the text character's current scale.
When a number, it is scaled uniformly.
Given a 2D vector, it is scaled independently along the X and Y axis.
angle?: number
Increases the amount of degrees to rotate the text character.
color?: Color
Color transformation applied to the text character.
Multiplies the current color with this color.
opacity?: number
Opacity multiplication applied to the text character.
For example, an opacity of 0.4 with 2 set in the transformation, the resulting opacity will be 0.8 (0.4 × 2).
override?: boolean
If true, the styles applied by this specific entry transform
will override, rather than compose with, the default styles given in and by other
components' styles.
BoomOpt:
group
Options
speed?: number
Animation speed.
scale?: number
Scale.
comps?: CompList<any>
Additional components.
since
v3000.0
LevelOpt:
group
Options
tileWidth: number
Width of each block.
tileHeight: number
Height of each block.
pos?: Vec2
Position of the first block.
tiles: {}
Definition of each tile.
wildcardTile?(sym: string, pos: Vec2): CompList | null | undefined
Called when encountered a symbol not defined in "tiles".
GetOpt: recursive?: boolean
Recursively get all children and their descendants.
liveUpdate?: boolean
Live update the returned list every time object is added / removed.
only?: "tags" | "comps"
Get only by tags or components.
group
Options
QueryOpt: include?: string | string[]
All objects which include all or any of these tags, depending on includeOp.
includeOp?: "and" | "or"
Selects the operator to use. Defaults to and.
exclude?: string | string[]
All objects which do not have all or any of these tags, depending on excludeOp.
excludeOp?: "and" | "or"
Selects the operator to use. Defaults to and.
distance?: number
All objects which are near or far to the position of this, depending on distanceOp.
distanceOp?: "near" | "far"
Selects the operator to use. Defaults to near.
visible?: boolean
All objects visible from this standpoint.
hierarchy?: "children" | "siblings" | "ancestors" | "descendants"
All objects in the given group. Defaults to children.
group
Options
PathFindOpt: allowDiagonals?: boolean
group
Options
layer(name: string): LayerComp
Determines the layer for objects. Object will be drawn on top if the layer index is higher.
param
name- The layer name to set.
// 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
returns
The layer comp.
since
v3001.0
group
Layer
onCollideEnd(t1: Tag, t2: Tag, action: (a: GameObj, b: GameObj, col?: Collision)=>void): KEventController
Register an event that runs once frame when 2 game objs with certain tags stops colliding (required to have area() component).
param
t1- The tag of the first game obj.
param
t2- The tag of the second game obj.
param
action- The function to run when the event is triggered.
onCollideEnd("bean", "earth", () => {
debug.log("destroying world in 3... 2... 1...")
});
returns
The event controller.
since
v3000.0
group
Physics
setGravity(g: number): void
Set gravity.
param
g- The gravity to set.
since
v2000.0
group
Physics
getGravity(): number
Get gravity.
since
v3001.0
group
Physics
setGravityDirection(d: Vec2): void
Set gravity direction.
since
v3001.0
group
Physics
getGravityDirection(): Vec2
Get gravity direction.
returns
The gravity direction.
since
v3001.0
group
Physics
setCamPos(pos: Vec2): void
Set camera position.
param
pos- The position to set the camera to.
// move camera to (100, 100)
setCamPos(100, 100);
setCamPos(vec2(100, 100));
setCamPos(100); // x and y are the same
since
v3001.10
group
Camera
setCamPos(x: number, y: number): void
setCamPos(xy: number): void
getCamPos(): Vec2
Get camera position.
returns
The current camera position.
since
v3001.10
group
Camera
setCamScale(scale: Vec2): void
Set camera scale.
param
scale- The scale to set the camera to.
// set camera scale to (2, 2)
setCamScale(2, 2);
setCamScale(vec2(2, 2));
setCamScale(2); // x and y are the same
since
v3001.10
group
Camera
setCamScale(x: number, y: number): void
setCamScale(xy: number): void
getCamScale(): Vec2
Get camera scale.
returns
The current camera scale.
since
v3001.10
group
Camera
setCamRot(angle: number): void
Set camera rotation.
param
angle- The angle to rotate the camera.
// rotate camera 90 degrees
setCamRot(90);
since
v3001.10
group
Camera
getCamRot(): number
Get camera rotation.
returns
The current camera rotation.
since
v3001.10
group
Camera
getCamTransform(): Mat4
Get camera transform.
returns
The current camera transform.
since
v3001.10
group
Camera
shake(intensity?: number): void
Camera shake.
param
intensity- The intensity of the shake. Default to 12.
// shake intensively when bean collides with a "bomb"
bean.onCollide("bomb", () => {
shake(120)
})
since
v3000.0
group
Camera
flash(flashColor: Color, fadeOutTime: number): TimerController
Camera flash.
param
flashColor- The color of the flash.
param
fadeOutTime- The time it takes for the flash to fade out.
onClick(() => {
// flashed
flash(WHITE, 0.5);
});
returns
A timer controller.
since
v3001.0
group
Camera
camPos(pos: Vec2): Vec2
param
pos- The position to set the camera to.
deprecated
Use
// camera follows player
player.onUpdate(() => {
camPos(player.pos)
})
returns
The current camera position.
since
v2000.0
group
Camera
camPos(x: number, y: number): Vec2
deprecated
camPos(xy: number): Vec2
deprecated
camPos(): Vec2
deprecated
camScale(scale: Vec2): Vec2
param
scale- The scale to set the camera to.
deprecated
Use
returns
The current camera scale.
since
v2000.0
group
Camera
camScale(x: number, y: number): Vec2
deprecated
camScale(xy: number): Vec2
deprecated
camScale(): Vec2
deprecated
camRot(angle?: number): number
param
angle- The angle to rotate the camera.
deprecated
Use
returns
The current camera rotation.
since
v2000.0
group
Camera
camFlash(flashColor: Color, fadeOutTime: number): TimerController
param
flashColor- The color of the flash.
param
fadeOutTime- The time it takes for the flash to fade out.
deprecated
use
returns
A timer controller.
since
v3001.0
group
Camera
camTransform(): Mat4
deprecated
use
group
Camera
toScreen(p: Vec2): Vec2
Transform a point from world position (relative to the root) to screen position (relative to the screen).
param
p- The point to transform.
since
v3001.0
group
Camera
toWorld(p: Vec2): Vec2
Transform a point from screen position (relative to the screen) to world position (relative to the root).
param
p- The point to transform.
since
v3001.0
group
Camera
play(src: string | SoundData | Asset | MusicData | Asset, options?: AudioPlayOpt): AudioPlay
Play a piece of audio.
// play a one off sound
play("wooosh")
// play a looping soundtrack (check out AudioPlayOpt for more options)
const music = play("OverworldlyFoe", {
volume: 0.8,
loop: true
})
// using the handle to control (check out AudioPlay for more controls / info)
music.paused = true
music.speed = 1.2
returns
A control handle.
since
v2000.0
group
Audio
burp(options?: AudioPlayOpt): AudioPlay
Yep. Plays a burp sound.
returns
A control handle.
since
v2000.0
group
Audio
setVolume(v: number): void
Set the global volume.
param
v- The volume to set.
setVolume(0.5)
since
v3001.10
group
Audio
getVolume(): number
Get the global volume.
returns
The current volume.
since
v3001.10
group
Audio
volume(v?: number): number
deprecated
Use
// makes everything quieter
volume(0.5)
returns
The new volume or the current volume.
since
v2000.0
group
Audio
audioCtx: AudioContext
Get the underlying browser AudioContext.
since
v2000.0
group
Audio
rand<T>(a?: T, b?: T): T
Get a random value between the given bound.
param
a- The lower bound. If not upper bound, this is the upper bound and the lower bound is 0.
param
b- The upper bound.
// a random number between 0 - 8
rand(8)
// a random point on screen
rand(vec2(width(), height()))
// a random color
rand(rgb(255, 255, 255))
// a random number between 50 - 100
rand(50, 100);
// a random point on screen with x between 20 - 100 and y between 20 - 100
rand(vec2(20), vec2(100));
// spawn something on the right side of the screen but with random y value within screen height
add([
pos(width(), rand(0, height())),
]);
since
v2000.0
group
Random
randi(a?: number, b?: number): number
rand() but floored to integer. If not arguments, returns 0 or 1.
param
a- The lower bound. If not upper bound, this is the upper bound.
param
b- The upper bound.
randi(); // returns either 0 or 1
randi(10); // returns a random integer between 0 and 9
randi(10, 20); // returns a random integer between 10 and 19
returns
A random integer between 0 and 1.
since
v2000.0
group
Random
randSeed(seed?: number): number
Get / set the random number generator seed.
param
seed- The seed to set.
randSeed(Date.now())
returns
The new seed.
since
v2000.0
group
Random
choose<T>(lst: T[]): T
Choose a random item from a list.
param
lst- The list to choose from.
// decide the best fruit randomly
const bestFruit = choose(["apple", "banana", "pear", "watermelon"]);
returns
A random item from the list.
since
v3001.0
group
Random
chooseMultiple<T>(lst: T[], count: number): T[]
Choose multiple random items from a list.
param
lst- The list to choose from.
param
count- The number of items to choose.
returns
An array of random items from the list.
since
v3001.0
group
Random
shuffle<T>(lst: T[]): T[]
Shuffle an array.
param
lst- The list to shuffle.
returns
A shuffled array.
since
v3001.0
group
Random
setLayers(layers: string[], defaultLayer: string): void
Define the layer names. Should be called before any objects are made.
param
layers- The layer names.
param
defaultLayer- The default layer name.
layers(["bg", "obj", "ui"], "obj")
// no layer specified, will be added to "obj"
add([
sprite("bean"),
]);
// add to "bg" layer
add([
sprite("bg"),
layer("bg"),
]);
since
v3001.10
group
Layers
getLayers(): string[] | null
Get the layer names.
returns
The layer names or null if not set.
since
v3001.10
group
Layers
experimental
This feature is in experimental phase, it will be fully released in v4000.0
getDefaultLayer(): string | null
Get the default layer name.
returns
The default layer name or null if not set.
since
v3001.0.5
group
Layers
experimental
This feature is in experimental phase, it will be fully released in v4000.0
addLevel(map: string[], opt: LevelOpt): GameObj<PosComp | LevelComp>
Construct a level based on symbols.
param
map- The map data.
param
opt- The level options.
addLevel([
" $",
" $",
" $$ = $",
" % ==== = $",
" = ",
" ^^ = > = &",
"===========================",
], {
// define the size of tile block
tileWidth: 32,
tileHeight: 32,
// define what each symbol means, by a function returning a component list (what will be passed to add())
tiles: {
"=": () => [
sprite("floor"),
area(),
body({ isStatic: true }),
],
"$": () => [
sprite("coin"),
area(),
pos(0, -9),
],
"^": () => [
sprite("spike"),
area(),
"danger",
],
}
})
returns
A game obj with the level.
since
v2000.0
group
Level
getData<T>(key: string, def?: T): T | null
Get data from local storage, if not present can set to a default value.
param
key- The key to get data from.
param
def- The default value to set if not found.
returns
The data or null if not found.
since
v2000.0
group
Data
setData(key: string, data: any): void
Set data from local storage.
param
key- The key to set data to.
param
data- The data to set.
since
v2000.0
group
Data
screenshot(): string
Take a screenshot and get the data url of the image.
returns
The dataURL of the image.
since
v2000.0
group
Data
download(filename: string, dataurl: string): void
Trigger a file download from a url.
since
v3000.0
group
Data
downloadText(filename: string, text: string): void
Trigger a text file download.
since
v3000.0
group
Data
downloadJSON(filename: string, data: any): void
Trigger a json download from a .
since
v3000.0
group
Data
downloadBlob(filename: string, blob: Blob): void
Trigger a file download from a blob.
since
v3000.0
group
Data
record(frameRate?: number): Recording
Start recording the canvas into a video. If framerate is not specified, a new frame will be captured each time the canvas changes.
returns
A control handle.
since
v2000.1
group
Data
Recording:
Screen recording control handle.
group
Data
pause(): void
Pause the recording.
resume(): void
Resume the recording.
stop(): Promise<Blob>
Stop the recording and get the video data as mp4 Blob.
since
v3000.0
download(filename?: string): void
Stop the recording and downloads the file as mp4. Trying to resume later will lead to error.
debug: Debug
The Debug interface for debugging stuff.
// pause the whole game
debug.paused = true
// enter inspect mode
debug.inspect = true
returns
The debug interface.
since
v2000.0
group
Debug
Debug:
group
Debug
paused: boolean
Pause the whole game.
inspect: boolean
Draw bounding boxes of all objects with `area()` component, hover to inspect their states.
timeScale: number
Global time scale.
showLog: boolean
Show the debug log or not.
fps(): number
Current frames per second.
numFrames(): number
Total number of frames elapsed.
since
v3000.0
drawCalls(): number
Number of draw calls made last frame.
stepFrame(): void
Step to the next frame. Useful with pausing.
clearLog(): void
Clear the debug log.
log(msg: any): void
Log some text to on screen debug log.
error(msg: any): void
Log an error message to on screen debug log.
curRecording: Recording | null
The recording handle if currently in recording mode.
since
v2000.1
numObjects(): number
Get total number of objects.
since
v3001.0
plug<T>(plugin: KAPLAYPlugin): KAPLAYCtx & T
Import a plugin.
param
plugin- The plugin to import.
returns
The updated context with the plugin.
since
v2000.0
group
Plugins
KAPLAYPlugin<T>(k: KAPLAYCtx): T | (args: any)=>(k: KAPLAYCtx)=>T
A plugin for KAPLAY.
// a plugin that adds a new function to KAPLAY
const myPlugin = (k) => ({
myFunc: () => {
k.debug.log("hello from my plugin")
}
})
// use the plugin
kaplay({
plugins: [ myPlugin ]
})
// now you can use the new function
myFunc()
group
Plugins
ASCII_CHARS: string
All chars in ASCII.
since
v2000.0
group
Constants
LEFT: Vec2
Left directional vector vec2(-1, 0).
since
v2000.0
group
Constants
RIGHT: Vec2
Right directional vector vec2(1, 0).
since
v2000.0
group
Constants
UP: Vec2
Up directional vector vec2(0, -1).
since
v2000.0
group
Constants
DOWN: Vec2
Down directional vector vec2(0, 1).
since
v2000.0
group
Constants
RED: Color
Red color.
since
v2000.0
group
Constants
GREEN: Color
Green color.
since
v2000.0
group
Constants
BLUE: Color
Blue color.
since
v2000.0
group
Constants
YELLOW: Color
Yellow color.
since
v2000.0
group
Constants
MAGENTA: Color
Cyan color.
since
v2000.0
group
Constants
CYAN: Color
Cyan color.
since
v2000.0
group
Constants
WHITE: Color
White color.
since
v2000.0
group
Constants
BLACK: Color
Black color.
since
v2000.0
group
Constants