Function
(gopt?: KAPLAYOpt): KAPLAYCtx 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
Constant
: () => void End everything.
Interface
: KAPLAY configurations.
?: number Height of game.
?: number Pixel scale / size.
?: boolean Keep aspect ratio and leave black bars on remaining spaces.
?: boolean If register debug buttons (default true)
?: Key Key that toggles debug mode
?: string Default font (defaults to "monospace").
?: number Device pixel scale (defaults to 1, high pixel density will hurt performance).
?: boolean Disable antialias and enable sharp pixel display. If you see rendering artifacts, set pixelDensity
param to Math.min(devicePixelRatio, 2)
and scale
to FHD resolution (e.g. 960x540 would need scale 2). Will result in up to 4K.
?: HTMLCanvasElement The canvas DOM element to use. If empty will create one.
?: HTMLElement The container DOM element to insert the canvas if created. Defaults to document.body.
?: RGBValue | RGBAValue | string Background color. E.g. [ 0, 0, 255 ] for solid blue background, or [ 0, 0, 0, 0 ] for transparent background. Accepts RGB value array or string hex codes.
?: TexFilter Default texture filter.
?: number How many log messages can there be on one screen (default 8).
?: number How many seconds log messages stay on screen (default 4).
?: number Size of the spatial hash grid for collision detection (default 64).
?: boolean If translate touch events as mouse clicks (default true).
?: boolean If KAPLAY should render a default loading screen when assets are not fully ready (default true).
?: boolean If pause audio when tab is not active (default false).
?: Record<string, GamepadDef> Custom gamepad definitions (see gamepad.json for reference of the format).
?: TButtonDef Defined buttons for input binding.
?: number Limit framerate to an amount per second.
?: boolean If focus on the canvas on start (default true).
?: boolean If import all KAPLAY functions to global (default true).
?: TPlugin List of plugins to import.
?: boolean Enter burp mode.
?: boolean Make components ids be added as tags.
That means .is() will return true for components with that id.
?: number Padding used when adding sprites to texture atlas.
?: boolean If the debug inspect view should ignore objects that are paused when choosing
the object to show the inspect view on.
default
false
experimental
?: string Which strategy to use for narrow phase collision, gjk or sat
?: number Timeout (in milliseconds) at which other loaders waiting on sprites will give
up and throw an error.
Currently this is only used by .
Constant
: (msg: string) => void Throws a new error and show up the Blue Screen.
param
unknown- The message for showing in the Blue Screen.
since
v4000.0
group
Start
Function
(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
subgroup
Util
Function
(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
subgroup
Sprites
Function
(src: LoadSpriteSrc, data: SpriteAtlasData): Asset<Record<string, SpriteData>> 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
subgroup
Sprites
Function
(src: LoadSpriteSrc, url: string): Asset<Record<string, SpriteData>> 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
subgroup
Sprites
Function
(name: string | null, imgSrc: LoadSpriteSrc, jsonSrc: string | AsepriteData): Asset<SpriteData> Load a sprite with aseprite spritesheet json (should use "array" in the export options and have tags enabled, that way kaplay can load tagged frames as animations).
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
subgroup
Sprites
Function
(name?: string): Asset<SpriteData> Load default sprite "bean".
param
name- An optional name for bean.
loadBean();
// use it right away
add([
sprite("bean"),
]);
returns
The asset data.
since
v2000.0
group
Assets
subgroup
Sprites
Function
(name?: string, opt?: LoadBitmapFontOpt): Asset<BitmapFontData> Load default font "happy".
param
name- Optional name for happy. Default to happy.
param
opt- Optional config for
loadHappy();
add([
text("ohhi", { font: "happy" }),
]);
returns
The asset data.
since
v4000.0
group
Assets
subgroup
Fonts
Function
(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
subgroup
Util
Function
(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
subgroup
Audio
Function
(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
subgroup
Audio
Function
(name: string, src: string | ArrayBuffer | ArrayBufferView, 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
subgroup
Fonts
Function
(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
subgroup
Fonts
Function
(sprite: string, chars: string): Asset<BitmapFontData> Define the frames of an existing sprite as characters that can be used as a font.
This was primarily intended for use with loadSpriteAtlas because the sprite in
question usually isn't the whole image and so can't be also passed to loadBitmapFont
as its own font.
This waits for the sprite to load before doing anything, but if the sprite doesn't load, the game
will transition to the error screen after a timeout (which is set by ).
param
sprite- The ID of the sprite to use as a font. Must already have frames defined
param
chars- The characters that correspond to each of the frames in the sprite. You can't use
space or newline here because those are hard-coded to special behaviors in the text layout code.
returns
The generated font data.
group
Assets
subgroup
Fonts
see
Function
(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
subgroup
Shaders
Function
(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")
returns
The asset data.
since
v3000.0
group
Assets
subgroup
Shaders
Function
(l: Promise<T>): 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
subgroup
Util
Constant
: (name: string, url: string) => Asset<SerializedGameObj> Load a prefab.
since
v4000.0.0
group
Assets
subgroup
Util
experimental
Function
(): number Get the global asset loading progress (0.0 - 1.0).
returns
The loading progress.
since
v3000.0
group
Assets
subgroup
Util
Function
(name: string): Asset<SpriteData> | null Get SpriteData from name.
param
name- The asset name.
returns
The asset data.
since
v3000.0
group
Assets
subgroup
Getters
Function
(name: string): Asset<SoundData> | null Get SoundData from name.
param
name- The asset name.
returns
The asset data.
since
v3000.0
group
Assets
subgroup
Getters
Function
(name: string): Asset<FontData> | null Get FontData from name.
param
name- The asset name.
returns
The asset data.
since
v3000.0
group
Assets
subgroup
Getters
Function
(name: string): Asset<BitmapFontData> | null Get BitmapFontData from name.
param
name- The asset name.
returns
The asset data.
since
v3000.0
group
Assets
subgroup
Getters
Function
(name: string): Asset<ShaderData> | null Get ShaderData from name.
param
name- The asset name.
returns
The asset data.
since
v3000.0
group
Assets
subgroup
Getters
Function
(name: string): Asset<any> | null Get custom data from name.
param
name- The asset name.
returns
The asset data.
since
v3000.0
group
Assets
subgroup
Getters
Class
: An asset is a resource that is loaded asynchronously.
It can be a sprite, a sound, a font, a shader, etc.
static (data: D)
=> Asset<D> (action: (data: D) => void)
=> this (action: (err: Error) => void)
=> this (action: () => void)
=> this (action: (data: D) => void)
=> Asset<D> (action: (err: Error) => void)
=> Asset<D> (action: () => void)
=> Asset<D> Class
: static (src: LoadSpriteSrc, opt?: LoadSpriteOpt)
=> Promise<SpriteData> static (data: ImageSource, opt?: LoadSpriteOpt)
=> SpriteData static (url: string, opt?: LoadSpriteOpt)
=> Promise<SpriteData> Class
: static (buf: AudioBuffer)
=> SoundData static (buf: ArrayBuffer)
=> Promise<SoundData> static (url: string)
=> Promise<SoundData> Type
: Shader group
Assets
subgroup
Data
Interface
: group
Assets
subgroup
Types
Type
: GfxFont group
Assets
subgroup
Data
Interface
: group
Assets
subgroup
Types
?: string A string of characters to map to every sprite in the characters grid
default
" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
Class
: group
Assets
subgroup
Data
Type
: number | { ?: number The starting frame.
?: boolean If this anim should be played in loop.
?: boolean When looping should it move back instead of go to start frame again.
?: number This anim's speed in frames per second.
?: number[] List of frames for the animation.
If this property exists, **from, to, and pingpong will be ignored**.
} Frame-based animation configuration.
group
Assets
subgroup
Types
Type
: Record<string, SpriteAnim> A dict of name <-> animation.
group
Assets
subgroup
Types
Interface
: Sprite loading options.
group
Assets
subgroup
Types
?: number If the defined area contains multiple sprites, how many frames are in the area horizontally.
?: number If the defined area contains multiple sprites, how many frames are in the area vertically.
?: NineSlice 9 slice sprite for proportional scaling.
?: Quad[] Individual frames.
?: SpriteAnims Animation configuration.
?: boolean If the sprite is a single image.
Type
: { : number The width of the 9-slice's left column.
: number The width of the 9-slice's right column.
: number The height of the 9-slice's top row.
: number The height of the 9-slice's bottom row.
} group
Assets
subgroup
Types
Type
: string | ImageSource Possible values for loading an sprite using loadSprite.
group
Assets
subgroup
Types
Class
: group
Assets
subgroup
Types
(name: string | null, loader: Promise<D>)
=> Asset<D> (name: string | null, data: D)
=> Asset<D> (handle: string)
=> Asset<D> | undefined ()
=> [string, Asset<D>][] (name: string, timeout: number)
=> PromiseLike<D> Type
: { : { : Array<{ : "forward" | "reverse" | "pingpong" }> } } group
Assets
subgroup
Data
Type
: Record<string, SpriteAtlasEntry> group
Assets
subgroup
Data
Type
: LoadSpriteOpt & { : number X position of the top left corner.
: number Y position of the top left corner.
: number Sprite area width.
: number Sprite area height.
} A sprite in a sprite atlas.
group
Assets
subgroup
Types
Type
: string group
Assets
subgroup
Data
Interface
: group
Assets
subgroup
Types
?: number The size to load the font in (default 64).
Type
: {} group
Assets
subgroup
Types
Type
: Exclude<TexImageSource, VideoFrame> group
Assets
subgroup
Types
Function
(comps?: CompList): GameObj 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.
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
Function
(nameOrObject: SerializedGameObj | string, compList?: [...T]): GameObj<T[number]> Assemble a game object from a prefab asset loaded with loadPrefab or using createPrefab.
loadPrefab("bean", "/prefabs/bean.kaprefab")
addPrefab("bean", [
pos(40, 40)
])
returns
The added game object that contains all properties and methods each component offers.
group
Game Obj
Function
(name: string, obj: GameObj): SerializedGameObj Serialize a game object and register it (like loadPrefab does).
param
name- Name to register the prefab.
param
obj- The game object to serialize.
const beanObj = add([ sprite("bean") ]);
createPrefab("bean", beanObj);
addPrefab("bean"); // Now you can use as prefab
returns
The serialized game object.
since
v4000.0
group
Game Obj
Function
(obj: GameObj): SerializedGameObj Serialize a game object.
param
obj- The game object to serialize.
const beanObj = add([ sprite("bean") ]);
const beanPrefab = createPrefab(beanObj);
addPrefab(beanPrefab); // Now you can use as prefab
returns
The serialized game object.
since
v4000.0
group
Game Obj
subgroup
Prefabs
Function
(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
Function
(tag: Tag | Tag[], opts?: GetOpt): GameObj<T>[] 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 });
// Get a live query which updates in real-time
const allObjs = get("*", { liveUpdate: true });
returns
A list of game objects that have the tag.
since
v2000.0
group
Game Obj
Function
(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]
// get all visible friends
query({
include: "friend",
visible: true,
});
// get all friends less than 150 pixels from bean
bean.query({
include: "friend",
distance: 150,
});
group
Game Obj
Function
(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
Function
(tag: Tag): void 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
Function
(): GameObj Get the root of all objects.
returns
The root object.
since
v2000.0
group
Game Obj
Function
(map: string[], opt: AddLevelOpt, parent?: GameObj): GameObj<PosComp | LevelComp> Construct a level based on symbols.
param
map- The map data.
param
opt- The level options.
param
parent- The parent object of the level. Defaults to root.
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
Game Obj
see
Function
(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
Game Obj
Enum
:
Interface
: A serialized game object. Created using method.
since
v4000.0
group
Game Obj
subgroup
Prefabs
Interface
: Base interface of all game objects.
since
v2000.0
group
Game Obj
subgroup
Types
: GameObj[] Get all children game objects.
: string[] Get the tags of a game object. For update it, use tag()
and untag()
.
: Mat23 Calculated transform matrix of a game object.
: boolean If draw the game obj (run "draw" event or not).
: boolean If update the game obj (run "update" event or not).
?: RenderTarget The canvas to draw this game object on
(p: GameObj, opt: SetParentOpt): void Set the parent game obj with additional options.
(comps?: CompList): GameObj Add a child.
param
comps- The components to add.
returns
The added game object.
since
v3000.0
(nameOrObject:
Parsing error with ObjectKeyword
| string, compList?: [...T]): GameObj<T[number]> Add a prefab.
param
nameOrObject- Name of registered prefab using loadPrefab() or plain obj returned by createPrefab().
returns
The added game object.
since
v4000.0
(): SerializedGameObj Create a serialized version of this Game Object.
returns
The serialized game object
since
v4000.0
(obj: GameObj<T>): 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
(obj: GameObj): void Remove a child.
param
obj- The game object to remove.
since
v3000.0
(tag: Tag): void Remove all children with a certain tag.
param
tag- The tag to remove.
since
v3000.0
(): void Remove all children.
(): void Remove this game obj from scene.
(): boolean If game obj is attached to the scene graph.
returns
true if attached, false otherwise.
since
v2000.0
(obj: GameObj): boolean Check if is an ancestor (recursive parent) of another game object
returns
true if is ancestor, false otherwise.
since
v3000.0
(tag: Tag | Tag[], opts?: GetOpt): GameObj<T>[] Get a list of all game objs with certain tag.
param
tag- The tag to get.
since
v3000.0
(opt: QueryOpt): GameObj[] Get a list of all game objs with certain properties.
param
opt- The properties to get.
since
v3001.0
(): void Update this game object and all children game objects.
(): void Update this game object and all children game objects.
(): void Draw this game object and all children game objects.
(): GameObjInspect Gather debug info of all comps.
: () => void Draw debug info in inspect mode
(objects: GameObj<any>[]): void This method is called to transform and collect objects which should be drawn layered
(comp: Comp): void Add a component.
const obj = add([
sprite("bean"),
]);
// Add opacity
obj.use(opacity(0.5));
since
v2000.0
(comp: string): 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
(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 v3001.1.0
(id: string): Comp | null Get state for a specific comp.
param
id- The component id.
since
v2000.0
(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 v3001.1.0
(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 v3001.1.0
(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 v3001.1.0
(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
(event: string, args: any): void Trigger an event.
param
event- The event name.
param
args- The arguments to pass to the event action.
since
v2000.0
: () => void Clear all events.
(action: () => void): KEventController Register an event that runs when the game obj is added to the scene.
returns
The event controller.
since
v2000.0
(action: () => void): KEventController Register an event that runs every frame as long as the game obj exists.
returns
The event controller.
since
v2000.1
(action: () => void): KEventController Register an event that runs every frame as long as the game obj exists.
returns
The event controller.
since
v2000.1
(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
(action: () => void): KEventController Register an event that runs when the game obj is destroyed.
returns
The event controller.
since
v2000.1
(action: (id: string) => void): KEventController Register an event that runs when a component is used.
returns
The event controller.
since
v4000.0
(action: (id: string) => void): KEventController Register an event that runs when a component is unused.
returns
The event controller.
since
v4000.0
(action: (tag: string) => void): KEventController Register an event that runs when a tag is added.
returns
The event controller.
since
v4000.0
(action: (tag: string) => void): KEventController Register an event that runs when a tag is removed.
returns
The event controller.
since
v4000.0
: KAPLAYCtx["onKeyPress"] : KAPLAYCtx["onKeyPressRepeat"] : KAPLAYCtx["onKeyRelease"] : KAPLAYCtx["onCharInput"] : KAPLAYCtx["onMouseDown"] : KAPLAYCtx["onMousePress"] : KAPLAYCtx["onMouseRelease"] : KAPLAYCtx["onMouseMove"] : KAPLAYCtx["onTouchStart"] : KAPLAYCtx["onTouchMove"] : KAPLAYCtx["onTouchEnd"] : KAPLAYCtx["onGamepadButtonDown"] : KAPLAYCtx["onGamepadButtonPress"] : KAPLAYCtx["onGamepadButtonRelease"] : KAPLAYCtx["onGamepadStick"] : KAPLAYCtx["onButtonDown"] : KAPLAYCtx["onButtonPress"] : KAPLAYCtx["onButtonRelease"] Interface
: group
Game Obj
subgroup
Types
?: number Animation speed.
?: CompList<any> Additional components.
Interface
: Options for the addLevel.
group
Game Obj
subgroup
Types
?: Vec2 Position of the first block.
Type
: GameObjRaw & MergeComps<T> The basic unit of object in KAPLAY. The player, a butterfly, a tree, or even a piece of text.
group
Game Obj
subgroup
Types
Type
: { ?: boolean Recursively get all children and their descendants.
?: boolean Live update the returned list every time object is added / removed.
?: "tags" | "comps" Get only by tags or components.
} group
Game Obj
subgroup
Types
Type
: { ?: string | string[] All objects which include all or any of these tags, depending on includeOp.
?: "and" | "or" Selects the operator to use. Defaults to and.
?: string | string[] All objects which do not have all or any of these tags, depending on excludeOp.
?: "and" | "or" Selects the operator to use. Defaults to and.
?: number All objects which are near or far to the position of this, depending on distanceOp.
?: "near" | "far" Selects the operator to use. Defaults to near.
?: boolean All objects visible from this standpoint.
?: "children" | "siblings" | "ancestors" | "descendants" All objects in the given group. Defaults to children.
} group
Game Obj
subgroup
Types
Type
: number A valid game object id.
group
Game Obj
subgroup
GameObjID
Function
(x: number, y: number): PosComp Set the position of a Game Object, relative to its parent.
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)
let bean =add([
pos(100, 200),
sprite("bean"),
]);
// This game object will draw a rectangle at (105, 205) world coordinate.
// The position will be 5 pixels to the right and 5 pixels down from the parent bean.
let rect = bean.add([
pos(5, 5),
rect(100, 100),
])
returns
The position comp.
since
v2000.0
group
Components
subgroup
Transform
Function
(xy: number): PosComp Function
(p: Vec2): PosComp Function
(): PosComp Function
(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
subgroup
Transform
Function
(xy: number): ScaleComp Function
(s: Vec2): ScaleComp Function
(): ScaleComp Function
(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
subgroup
Transform
Function
(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
subgroup
Rendering
Function
(c: Color): ColorComp Function
(rgb: [number, number, number]): ColorComp Function
(c: CSSColor & (string | {})): ColorComp Function
(): ColorComp Function
(blend: BlendMode): BlendComp Sets the blend mode of a Game Object.
// light
add([
sprite("light"),
blend(BlendMode.Add),
]);
returns
The blend comp.
since
v4000.0
group
Components
subgroup
Rendering
Function
(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
subgroup
Rendering
Function
(spr: string | SpriteData | Asset<SpriteData>, 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
subgroup
Rendering
Function
(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
subgroup
Rendering
Function
(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
subgroup
Rendering
Function
(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
subgroup
Rendering
Function
(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
subgroup
Rendering
Function
(radiusX: number, radiusY: number): EllipseComp Attach and render an ellipse to a Game Object.
param
radiusX- The radius of the ellipse on the x-axis.
param
radiusY- The radius of the ellipse on the y-axis.
add([
pos(80, 120),
ellipse(16, 8),
])
returns
The ellipse comp.
since
v2000.0
group
Components
subgroup
Rendering
Function
(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
subgroup
Rendering
Function
(url: string, opt?: VideoCompOpt): VideoComp Draws a video.
param
url- The video to play. Needs to be on the same webserver due to CORS.
param
opt- The video component options
returns
The video comp.
since
v4000.0
group
Components
subgroup
Rendering
Function
(picture: Picture): PictureComp Draws a picture, using the Picture API.
param
picture- The picture to draw.
returns
The picture comp.
since
v4000.0
group
Components
subgroup
Rendering
Function
(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
subgroup
Physics
Function
(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
subgroup
Rendering
Function
(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
subgroup
Transform
Function
(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
Components
subgroup
Rendering
Function
(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
subgroup
Rendering
Function
(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
subgroup
Rendering
Function
(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
subgroup
Physics
Function
(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
subgroup
Physics
Function
(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
subgroup
Physics
Function
(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
subgroup
Physics
Function
(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
subgroup
Physics
Function
(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
subgroup
Physics
Function
(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
subgroup
Physics
Function
(numJumps?: number): DoubleJumpComp Enables double jump.
param
numJumps- The number of jumps allowed. Defaults to 1.
returns
The double jump comp.
since
v3000.0
group
Components
subgroup
Physics
requires
Function
(dir: number | Vec2, speed: number): MoveComp 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.
// 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
subgroup
Behaviour
requires
Function
(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
subgroup
Behaviour
Function
(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
subgroup
Behaviour
Function
(id: string, uniform?: Uniform | ( () => Uniform)): ShaderComp Custom shader to manipulate sprite.
param
id- The shader id.
param
uniform- The uniform to pass to the shader.
returns
The shader comp.
since
v2000.0
group
Components
subgroup
Rendering
Function
(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
subgroup
UI
Function
(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
subgroup
Behaviour
Function
(fixed?: boolean): FixedComp Make a game obj unaffected by camera or parent object transforms, and render at last.
Useful for UI elements.
param
fixed- Default fixed value.
// 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
subgroup
Rendering
Function
(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
subgroup
Behaviour
Function
(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.hp--;
bad.hp--;
})
player.onCollide("apple", () => {
player.hp++;
})
player.onHurt(() => {
play("ouch")
})
// triggers when hp reaches 0
player.onDeath(() => {
destroy(player)
go("lose")
})
returns
The health comp.
since
v2000.0
group
Components
subgroup
Behaviour
Function
(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
subgroup
Behaviour
Function
(name: string): NamedComp Names an game obj.
param
name- The name to set.
returns
The named comp.
since
v3001.0
group
Components
subgroup
Behaviour
Function
(initialState: T, stateList?: T[]): StateComp<T> 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
subgroup
Behaviour
Function
(initialState: T, stateList: T[], transitions: Record<T, T | T[]>): StateComp<T> 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
subgroup
Behaviour
Function
(time: number): Comp deprecated
since v3001.0
Fade object in.
Uses opacity for finding what to fade into and to set opacity during fade animation.
returns
An empty comp.
since
v3000.0
group
Components
subgroup
Behaviour
requires
Function
(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
subgroup
Rendering
Function
(canvas: FrameBuffer | Picture, opt?: DrawonCompOpt): DrawonComp 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
subgroup
Rendering
Function
(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
subgroup
Behaviour
Function
(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
subgroup
Level
Function
(opt?: AnimateCompOpt): AnimateComp A component to animate properties.
This component has an internal clock which starts the moment it is added to an object.
param
opt- Options for the animate component. See
// First example
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",
});
// Second example
const obj = add([
area(),
color("#FF0000"),
animate(),
]);
// The internal clock starts when the object is added.
// We need to reset the animation when the object is hovered.
obj.onHover(() => {
obj.animation.seek(0); // reset the animation to the start
obj.animate(
"color",
// We can use the current color property as the start value.
// It doesn't make sense to have only one value in the array as it's a transition.
[obj.color, Color.fromHex("#0000FF")],
{ duration: 0.5, loops: 1 },
});
obj.onHoverEnd(() => {
// We need to unanimate the color property to reset it to the original value.
obj.unanimate("color");
obj.color = Color.fromHex("#FF0000");
});
returns
The animate comp.
since
v3001.0
group
Components
subgroup
Behaviour
Function
(opt?: FakeMouseOpt): FakeMouseComp A fake mouse that follows the mouse position and triggers events.
[Guide about fake mouse](https://v4000.kaplayjs.com/guides/fake_mouse/)
param
opt- Options for the fake mouse comp. See
returns
The fake mouse comp.
since
v3001.0
group
Components
subgroup
Behaviour
Function
(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
subgroup
Component Serialization
Function
(candidates: SentryCandidates, opt?: SentryCompOpt): SentryComp A sentry which reacts to objects coming into view.
returns
The sentry comp.
since
v3001.0
group
Components
subgroup
Level
Function
(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
subgroup
Level
Function
(opts: PathfinderCompOpt): PathfinderComp A navigator pathfinder which can calculate waypoints to a goal.
since
v3001.0
group
Components
subgroup
Level
Function
(map: string[], opt?: LevelCompOpt): LevelComp Construct a level based on symbols.
param
map- The map data.
param
opt- The level options.
param
unknown- The parent object of the level. Defaults to root.
const myLevel = add([
level([
" $",
" $",
" $$ = $",
" % ==== = $",
" = ",
" ^^ = > = &",
"===========================",
], {
// 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
v4000.0
group
Components
subgroup
Level
Interface
: A serialized color.
group
Components
subgroup
Component Serialization
Interface
: A serialized 2d vector.
group
Components
subgroup
Component Serialization
Interface
: The fakeMouse component.
group
Components
subgroup
Component Types
get (): boolean Whether the fake mouse is pressed.
(): void Trigger press (onClick).
(): void Trigger release.
(action: () => void): void Register an event that runs when the fake mouse performs a click.
(action: () => void): void Register an event that runs when the fake mouse releases.
Type
: { ?: boolean Whether the fake mouse should follow the real mouse. Defaults to true
.
} Options for the fakeMouse component.
group
Components
subgroup
Component Types
Interface
: The timer component.
group
Components
subgroup
Component Types
: number The maximum number of loops per frame allowed,
to keep loops with sub-frame intervals from freezing the game.
(time: number, action?: () => void): TimerController Run the callback after n seconds.
(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.
(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.
Interface
: The serialized fixed component.
group
Components
subgroup
Component Serialization
Interface
: The fixed component.
group
Components
subgroup
Component Types
: boolean If the obj is unaffected by camera
Interface
: The serialized pos component.
group
Components
subgroup
Component Serialization
Interface
: The pos component.
group
Components
subgroup
Component Types
: Vec2 Object's current world position.
(xVel: number, yVel: number): void Move how many pixels per second. If object is 'solid', it won't move into other 'solid' objects.
(dx: number, dy: number): void Move how many pixels, without multiplying dt, but still checking for 'solid'.
(dest: Vec2, speed?: number): void Move to a spot with a speed (pixels per second), teleports if speed is not given.
(x: number, y: number, speed?: number): void (newPos?: Vec2): Vec2 | null Get / Set the position of the object on the screen.
(newPos?: Vec2): Vec2 | null Get / Set the position of the object relative to the root.
(this: GameObj<PosComp | FixedComp>, p: Vec2): Vec2 Transform a local point (relative to this) to a screen point (relative to the camera)
(this: GameObj<PosComp>, p: Vec2): Vec2 Transform a local point (relative to this) to a world point (relative to the root)
(this: GameObj<PosComp | FixedComp>, p: Vec2): Vec2 Transform a screen point (relative to the camera) to a local point (relative to this)
(this: GameObj<PosComp>, p: Vec2): Vec2 Transform a world point (relative to the root) to a local point (relative to this)
(this: GameObj<PosComp>, other: GameObj<PosComp>, p: Vec2): Vec2 Transform a point relative to this to a point relative to other
(this: GameObj<PosComp>, other: GameObj<PosComp>, p: Vec2): Vec2 Transform a point relative to other to a point relative to this
(): SerializedPosComp Serialize the current state comp
Interface
: The serialized blend component.
group
Components
subgroup
Component Serialization
Interface
: The blend component.
group
Components
subgroup
Component Types
Interface
: The serialized circle component.
group
Components
subgroup
Component Serialization
Interface
: The circle component.
group
Components
subgroup
Component Types
: number Radius of circle.
(): Circle Render area of the circle.
Interface
: Options for the circle component.
group
Components
subgroup
Component Types
?: boolean If fill the circle (useful if you only want to render outline with
outline component).
Interface
: The serialized color component.
group
Components
subgroup
Component Serialization
Interface
: The color component.
group
Components
subgroup
Component Types
Type
: {} Options for the drawon component.
group
Components
subgroup
Component Types
Interface
: The drawon component.
group
Components
subgroup
Component Types
Interface
: The serialized ellipse component.
group
Components
subgroup
Component Serialization
Interface
: The ellipse component.
group
Components
subgroup
Component Types
: number Semi-major axis of ellipse.
: number Semi-minor axis of ellipse.
(): Ellipse Render area of the ellipse.
(): SerializedEllipseComp Interface
: Options for the ellipse component.
group
Components
subgroup
Component Types
?: boolean If fill is false, the ellipse is not filled (useful if you only want to render outline with
outline component).
Interface
: The serialized mask component.
group
Components
subgroup
Component Serialization
Interface
: The mask component.
group
Components
subgroup
Component Types
Interface
: The serialized opacity component.
group
Components
subgroup
Component Serialization
Interface
: The opacity component.
group
Components
subgroup
Component Types
: number Opacity of the current object.
(time?: number, easeFunc?: EaseFunc): TweenController Fade in at the start.
(time?: number, easeFunc?: EaseFunc): TweenController Fade out at the start.
(): SerializedOpacityComp Interface
: The serialized outline component.
group
Components
subgroup
Component Serialization
Interface
: The outline component.
group
Components
subgroup
Component Types
(): SerializedOutlineComp Type
: { ?: ShapeType Shape of the emitter. If given, particles spawn within this shape.
?: number Lifetime of the emitter.
?: number Rate of emission in particles per second if the emitter should emit out of itself.
: Vec2 Position (relative) of emission.
: number Direction of emission.
: number Spread (cone) of emission around the direction.
} Options for the particles's component.
group
Components
subgroup
Component Types
Type
: { : number Maximum number of simultaneously rendered particles.
?: [number, number] Minimum and maximum lifetime of a particle in seconds.
?: [number, number] Minimum and maximum speed of a particle in pixels per second.
?: [Vec2, Vec2] Minimum and maximum acceleration of a particle in pixels per second^2.
?: [number, number] Minimum and maximum damping of a particle.
?: [number, number] Minimum and maximum start angle of a particle.
?: [number, number] Minimum and maximum angular velocity of a particle.
?: number[] Scale from start to end for a particle.
?: Color[] Colors from start to end for a particle.
?: number[] Opacity from start to end for a particle.
?: Quad[] Quads from start to end for a particle.
: Texture Texture used for the particle.
} Options for the particles's component
group
Components
subgroup
Component Types
Interface
: The particles component.
group
Components
subgroup
Component Types
: { : Vec2 Relative position of the emitter
: number Relative direction of the emitter
} (n: number): void Emit a number of particles
(cb: () => void): void Called when the emitter expires
Interface
: The picture component.
group
Components
subgroup
Component Types
Type
: {} Options for the picture component.
group
Components
subgroup
Component Types
Interface
: The polygon component.
since
v3001.0
group
Components
subgroup
Component Types
: Vec2[] Points in the polygon.
?: number | number[] The radius of each corner.
?: Color[] The color of each vertex.
?: number[] The opacity of each vertex.
?: Vec2[] The uv of each vertex.
?: Texture The texture used when uv coordinates are present.
Type
: Omit<DrawPolygonOpt, "pts"> Options for the polygon component.
group
Components
subgroup
Component Types
Interface
: The serialized rect component.
group
Components
subgroup
Component Serialization
?: number | [number, number, number, number] Interface
: The rect component.
group
Components
subgroup
Component Types
: number Width of rectangle.
: number Height of rectangle.
?: number | [number, number, number, number] The radius of each corner.
Interface
: Options for the rect component.
group
Components
subgroup
Component Types
?: number | [number, number, number, number] Radius of the rectangle corners.
?: boolean If fill the rectangle (useful if you only want to render outline with outline() component).
Interface
: The serialized shader component.
group
Components
subgroup
Component Serialization
Interface
: The shader component.
group
Components
subgroup
Component Types
?: Uniform Uniform values to pass to the shader.
Type
: SpriteCompOpt & {} The serialized sprite component.
group
Components
subgroup
Component Serialization
Interface
: The sprite component.
group
Components
subgroup
Component Types
: string Name of the sprite.
: number Width for sprite.
: number Height for sprite.
: number Current frame in the entire spritesheet.
: number Current frame in relative to the animation that is currently playing.
: Quad The rectangular area of the texture to render.
(anim: string, options?: SpriteAnimPlayOpt): void Play a piece of anim.
(): void Stop current anim.
(): number Get total number of frames.
(): SpriteCurAnim | null Get the current animation data.
(): string | undefined Get current anim name.
deprecated
Use `getCurAnim().name` instead.
(name: string): boolean Check if object's sprite has an animation.
(name: string): SpriteAnim | null Get an animation.
: number Speed multiplier for all animations (for the actual fps for an anim use .play("anim", { speed: 10 })).
: boolean Flip texture horizontally.
: boolean Flip texture vertically.
(action: (anim: string) => void): KEventController Register an event that runs when an animation is played.
(action: (anim: string) => void): KEventController Register an event that runs when an animation is ended.
Interface
: Options for the sprite component.
group
Components
subgroup
Component Types
?: number If the sprite is loaded with multiple frames, or sliced, use the frame option to specify which frame to draw.
?: boolean If provided width and height, don't stretch but instead render tiled.
?: number Stretch sprite to a certain width.
?: number Stretch sprite to a certain height.
?: string Play an animation on start.
?: number Speed multiplier for all animations (for the actual fps for an anim use .play("anim", { speed: 10 })).
?: boolean Flip texture horizontally.
?: boolean Flip texture vertically.
?: Quad The rectangular sub-area of the texture to render, default to full texture quad(0, 0, 1, 1)
.
?: boolean If fill the sprite (useful if you only want to render outline with outline() component).
Interface
: The serialized text component.
group
Components
subgroup
Component Serialization
Interface
: The text component.
group
Components
subgroup
Component Types
: string The text to render.
: string | BitmapFontData The font to use.
: TextAlign Text alignment ("left", "center" or "right", default "left").
: number The gap between each line.
: number The gap between each character.
: CharTransform | CharTransformFunc Transform the pos, scale, rotation or color for each character based on the index or char.
: Record<string, CharTransform | CharTransformFunc> Stylesheet for styled chunks, in the syntax of "this is a [style]text[/style] word".
(): FormattedText The text data object after formatting, that contains the
renering info as well as the parse data of the formatting tags.
Interface
: Options for the text component.
group
Components
subgroup
Component Types
?: number Height of text.
?: string | BitmapFontData The font to use.
?: number Wrap text to a certain width.
?: TextAlign Text alignment ("left", "center" or "right", default "left").
?: number The gap between each line.
?: number The gap between each character.
?: CharTransform | CharTransformFunc Transform the pos, scale, rotation or color for each character based on the index or char.
?: Record<string, CharTransform | CharTransformFunc> Stylesheet for styled chunks, in the syntax of "this is a [style]text[/style] word".
?: 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.
Interface
: The uvquad component.
group
Components
subgroup
Component Types
: number Height of height.
Interface
: The agent component.
group
Components
subgroup
Component Types
(cb: () => void): KEventController (cb: () => void): KEventController (cb: () => void): KEventController (cb: () => void): KEventController Type
: {} Options for the agent component.
group
Components
subgroup
Component Types
Interface
: The level component.
group
Components
subgroup
Component Types
(sym: string, p: Vec2): GameObj | null Spawn a tile from a symbol defined previously.
(sym: string, x: number, y: number): GameObj | null (obj: CompList<T>, p: Vec2): GameObj<T> | null Spawn a tile from a component list.
returns
The spawned game object, or null if the obj hasn't components.
(sym: CompList<T>, x: number, y: number): GameObj<T> | null (): number Total width of level in pixels.
(): number Total height of level in pixels.
(tilePos: Vec2): GameObj[] Get all game objects that's currently inside a given tile.
(origin: Vec2, direction: Vec2): RaycastResult Raycast all game objects on the given path.
(tilePos: Vec2): Vec2 Convert tile position to pixel position.
(x: number, y: number): Vec2 (pos: Vec2): Vec2 Convert pixel position to tile position.
(x: number, y: number): Vec2 (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.
(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.
(cb: () => void): KEventController (cb: () => void): KEventController (cb: () => void): KEventController Interface
: Options for the level component.
group
Components
subgroup
Component Types
: number Width of each block.
: number Height of each block.
: {} Definition of each tile.
?: (sym: string, pos: Vec2) => CompList<Comp> | null | undefined Called when encountered a symbol not defined in "tiles".
Type
: {} group
Components
subgroup
Component Types
Interface
: The sentry component.
group
Components
subgroup
Component Types
?: Vec2 The direction the sentry is pointing to.
?: number The direction of the sentry as an angle in degrees.
?: number The field of view of the sentry in degrees.
: GameObj<any>[] The objects spotted most recently.
(cb: (objects: GameObj[]) => void): KEventController Attaches an event handler which is called when objects of interest are spotted.
param
cb- The event handler called when objects are spotted.
(obj: GameObj<PosComp>, direction?: Vec2, fieldOfView?: number): boolean Returns true if the object is within the field of view.
param
obj- The object to test.
param
direction- The direction to look at.
param
fieldOfView- The field of view in degrees.
(obj: GameObj<PosComp>): boolean Returns true if there is a line of sight to the object.
param
obj- The object to test.
Interface
: Options for the sentry component.
group
Components
subgroup
Component Types
?: Vec2 | number The direction the sentry is pointing to. If undefined, direction has no influence.
?: number The field of view of the sentry in degrees. If undefined, defaults to human fov of 200 degrees.
?: boolean If true, line of sight matters. This means that objects which are blocked from view by areas are invisible.
?: string[] When using line of sight, the objects which are transparent for the ray. Include at least a tag identifying the sentry.
?: number The frequency of checking, defaults to every second.
Interface
: The tile component.
group
Components
subgroup
Component Types
: Vec2 The tile position inside the level.
: boolean If the tile is an obstacle in pathfinding.
: number How much a tile is cost to traverse in pathfinding (default 0).
: Edge[] If the tile has hard edges that cannot pass in pathfinding.
: Vec2 Position offset when setting tilePos
.
Type
: { ?: boolean If the tile is an obstacle in pathfinding.
?: number How much a tile is cost to traverse in pathfinding (default 0).
?: Edge[] If the tile has hard edges that cannot pass in pathfinding.
?: Vec2 Position offset when setting tilePos
.
} Options for the tile component.
group
Components
subgroup
Component Types
Interface
: The serialized health component.
group
Components
subgroup
Component Serialization
Interface
: The health component.
group
Components
subgroup
Component Types
: number Current health points. Setting it to a lower or higher value will trigger onHurt() and onHeal().
Setting it to a value greater than maxHP will set it to maxHP.
Setting it to a value less than 0 will set it to 0 and trigger onDeath().
: number Max amount of HP.
: boolean Whether hp is 0.
(action: (deltaHP?: number) => void): KEventController Register an event that runs when the hp is lowered.
(action: (deltaHP?: number) => void): KEventController Register an event that runs when the hp is increased.
(action: () => void): KEventController Register an event that runs when object's HP becomes zero.
Interface
: The lifespan component.
group
Components
subgroup
Component Types
?: number Fade out duration (default 0 which is no fade out).
Interface
: The serialized color component.
group
Components
subgroup
Component Serialization
Interface
: The named component.
group
Components
subgroup
Component Types
Interface
: The serialized state component.
group
Components
subgroup
Component Serialization
: Record<string, string | string[]> Interface
: The state component.
group
Components
subgroup
Component Types
: (state: T, args: any) => void Enter a state, trigger onStateEnd for previous state and onStateEnter for the new State state.
(from: T, to: T, action: () => void): KEventController Register event that runs once when a specific state transition happens. Accepts arguments passed from enterState(name, ...args)
.
: (state: T, action: (args: any) => void) => KEventController Register event that runs once when enters a specific state. Accepts arguments passed from enterState(name, ...args)
.
: (state: T, action: () => void) => KEventController Register an event that runs once when leaves a specific state.
: (state: T, action: () => void) => KEventController Register an event that runs every frame when in a specific state.
: (state: T, action: () => void) => KEventController Register an event that runs every frame when in a specific state.
Interface
: The serialized stay component.
group
Components
subgroup
Component Serialization
Interface
: The stay component.
group
Components
subgroup
Component Types
: boolean If the obj should not be destroyed on scene switch.
?: string[] Array of scenes that the obj will stay on.
Interface
: The textInput component.
group
Components
subgroup
Component Types
: boolean Enable the text input array to be modified by user input.
Setting this to true is the same as calling focus(), and will
clear focus on all other active textInput objects.
: string The "real" text that the user typed, without any escaping.
(): void Focuses this text input so that it will receive input, and
removes focus from all other text inputs.
(cb: () => void): KEventController Event that runs when the text input gains focus.
(cb: () => void): KEventController Event that runs when the text input loses focus.
(cb: () => void): KEventController Event that runs when the user types any character in the text input
and causes its value to change.
This runs *after* the display text is updated with the escaped version
of the typed text, so in the event handler you can override the
displayed text with another version (like if you want to add syntax
highlighting or something). See also .
(cb: () => void): KEventController Runs immediately after onBlur if the value has changed while the text
input has been focused.
Interface
: The area component.
group
Components
subgroup
Component Types
: { : Shape | null If we use a custom shape over render shape.
: Cursor | null Cursor on hover.
} Collider area info.
: Tag[] If this object should ignore collisions against certain other objects.
?: number Restitution ("bounciness") of the object.
?: number Friction of the object.
(): boolean If was just clicked on last frame.
(): boolean If is being hovered on.
(other: GameObj<AreaComp>): Collision | null Check collision with another game obj.
(): Collision[] Get all collisions currently happening.
(o: GameObj<AreaComp>): boolean If is currently colliding with another game obj.
(o: GameObj<AreaComp>): boolean If is currently overlapping with another game obj (like isColliding, but will return false if the objects are just touching edges).
(f: () => void, btn?: MouseButton): KEventController Register an event runs when clicked.
(action: () => void): KEventController Register an event runs once when hovered.
(action: () => void): KEventController Register an event runs every frame when hovered.
(action: () => void): KEventController Register an event runs once when unhovered.
(tag: Tag, f: (obj: GameObj, col?: Collision) => void): KEventController Register an event runs once when collide with another game obj with certain tag.
(f: (obj: GameObj, col?: Collision) => void): KEventController Register an event runs once when collide with another game obj.
(tag: Tag, f: (obj: GameObj, col?: Collision) => void): KEventController Register an event runs every frame when collide with another game obj with certain tag.
(f: (obj: GameObj, col?: Collision) => void): KEventController Register an event runs every frame when collide with another game obj.
(tag: Tag, f: (obj: GameObj) => void): KEventController Register an event runs once when stopped colliding with another game obj with certain tag.
(f: (obj: GameObj) => void): void Register an event runs once when stopped colliding with another game obj.
(p: Vec2): boolean If has a certain point inside collider.
(obj: GameObj): void Push out from another solid game obj if currently overlapping.
(): Shape Get the geometry data for the collider in local coordinate space.
(): Shape Get the geometry data for the collider in world coordinate space.
(): Shape Get the geometry data for the collider in screen coordinate space.
Interface
: Options for the area component.
group
Components
subgroup
Component Types
?: 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)]) }),
])
?: number | Vec2 Area scale.
?: Cursor Cursor on hover.
?: Tag[] If this object should ignore collisions against certain other objects.
?: number Bounciness factor between 0 and 1.
?: number Friction factor between 0 and 1.
Interface
: The body component.
group
Components
subgroup
Component Types
: Vec2 Object current velocity.
: number How much velocity decays (velocity *= 1 / (1 + damping * dt) every frame).
: 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.
: number Initial speed in pixels per second for jump().
: number Gravity multiplier.
: number Mass of the body, decides how much a non-static body should move when resolves with another non-static body. (default 1).
?: boolean If object should move with moving platform (default true).
(): GameObj | null Current platform landing on.
(): boolean If currently landing on a platform.
(): boolean If currently falling.
(): boolean If currently rising.
(impulse: Vec2): void Applies an impulse
param
impulse- The impulse vector, applied directly
(force: Vec2): void Applies a force
param
force- The force vector, applied after scaled by the inverse mass
(force?: number): void Upward thrust.
(action: (col: Collision) => void): KEventController Register an event that runs when a collision is resolved.
(action: (col: Collision) => void): KEventController Register an event that runs before a collision would be resolved.
(action: () => void): KEventController Register an event that runs when the object is grounded.
(action: () => void): KEventController Register an event that runs when the object starts falling.
(action: () => void): KEventController Register an event that runs when the object falls off platform.
(action: () => void): KEventController Register an event that runs when the object bumps into something on the head.
(action: (obj: GameObj) => void): KEventController Register an event that runs when an object lands on this object.
(action: (obj: GameObj) => void): KEventController Register an event that runs when the object is bumped by another object head.
Interface
: Options for the body component.
group
Components
subgroup
Component Types
?: number How much velocity decays (velocity *= 1 / (1 + damping * dt) every frame).
?: number Initial speed in pixels per second for jump().
?: number Maximum velocity when falling.
?: number Gravity multiplier.
?: 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.
?: boolean If object should move with moving platform (default true).
?: number Mass of the body, decides how much a non-static body should move when resolves with another non-static body. (default 1).
Interface
: The doubleJump component.
group
Components
subgroup
Component Types
: number Number of jumps allowed.
(force?: number): void Performs double jump (the initial jump only happens if player is grounded).
(action: () => void): KEventController Register an event that runs when the object performs the second jump when double jumping.
Interface
: The serialized anchor component.
group
Components
subgroup
Component Serialization
Interface
: The anchor component.
group
Components
subgroup
Component Types
: Anchor | Vec2 Anchor point for render.
Interface
: The follow component.
group
Components
subgroup
Component Types
: { : GameObj The object to follow.
: Vec2 The offset to follow the object by.
} Interface
: The layer component.
group
Components
subgroup
Component Types
get (): number | null Get the index of the current layer the object is assigned to.
Will always be null
if the game doesn't use layers.
get (): string | null Get the name of the current layer the object is assigned to.
Will always be null
if the game doesn't use layers.
set (name: string)
Set the name of the layer the object should be assigned to.
Throws an error if the game uses layers and the requested layer
wasn't defined.
Interface
: The serialized move component.
group
Components
subgroup
Component Serialization
: SerializedVec2 | number Interface
: The move component.
group
Components
subgroup
Component Types
: () => SerializedMoveComp Interface
: The offscreen component.
group
Components
subgroup
Component Types
: 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.
(): boolean If object is currently out of view.
(action: () => void): KEventController Register an event that runs when object goes out of view.
(action: () => void): KEventController Register an event that runs when object enters view.
Interface
: Options for offscreen component.
group
Components
subgroup
Component Types
?: boolean If hide object when out of view.
?: boolean If pause object when out of view.
?: boolean If unpause object when back in view.
?: boolean If destroy object when out of view.
?: number The distance when out of view is triggered (default 200).
Interface
: The serialized rotate component.
group
Components
subgroup
Component Serialization
Interface
: The rotate component.
group
Components
subgroup
Component Types
: number Angle in degrees.
(angle: number): void Rotate in degrees.
(s: number): void Rotate to a degree (like directly assign to .angle)
Interface
: The serialized scale component.
group
Components
subgroup
Component Serialization
Interface
: The scale component.
group
Components
subgroup
Component Types
: Vec2 The current scale of the object
returns
The current scale of the object as a
(s: number): void Set the scale of the object to a number
(s: Vec2): void Set the scale of the object to a Vec2
(sx: number, sy: number): void Set the scale of the object to a number for x and y
(s: number): void Scale the object by a number
(s: Vec2): void Scale the object by a Vec2
(sx: number, sy: number): void Scale the object by a number for x and y
(): SerializedScaleComp Serialize the current state comp
Interface
: The serialized z component.
group
Components
subgroup
Component Serialization
Interface
: The z component.
group
Components
subgroup
Component Types
: number Defines the z-index of this game obj
(): SerializedZComp Serialize the current state comp
Type
: MergeObj<RemoveCompProps<T>> A type to merge the components of a game object, omitting the default component properties.
group
Components
subgroup
Component Types
Type
: (T | Tag)[] A component list.
group
Components
subgroup
Component Types
Interface
: Sprite animation configuration when playing.
group
Components
subgroup
Component Types
?: boolean If this anim should be played in loop.
?: boolean When looping should it move back instead of go to start frame again.
?: number This anim's speed in frames per second.
?: boolean If the animation should not restart from frame 1 and t=0 if it is already playing.
?: () => void Runs when this animation ends.
Interface
: group
Components
subgroup
Component Types
?: Tag[] What other comps this comp depends on.
?: () => void Event that runs when host game obj is added to scene.
?: () => void Event that runs at a fixed frame rate.
?: () => void Event that runs every frame.
?: () => void Event that runs every frame after update.
?: () => void Event that runs when obj is removed from scene.
?: () => string | null Debug info for inspect mode.
?: () => void Draw debug info in inspect mode.
?: () => any Serializes the component.
Type
: {} & Comp A component without own properties.
group
Components
subgroup
Component Types
Function
(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
subgroup
Mouse
Function
(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
Function
(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
subgroup
Keyboard
Function
(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
subgroup
Keyboard
Function
(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
subgroup
Keyboard
Function
(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
subgroup
Keyboard
Function
(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
subgroup
Keyboard
Function
(action: (k: Key) => void): KEventController Function
(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. See
param
action- The function that runs when a user releases certain keys
// release `a` or `b` keys
onKeyRelease([`a`, `b`], (k) => {
debug.log(`Released the ${k} key...`);
});
returns
The event controller.
since
v2000.1
group
Input
subgroup
Keyboard
Function
(action: (k: Key) => void): KEventController Register an event that runs when user releases a key.
param
action- The function that runs when a user releases a
// release a key
onKeyRelease((k) => {
debug.log(`Released the ${k} key...`);
});
returns
The event controller.
since
v2000.1
group
Input
Function
(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
subgroup
Keyboard
Function
(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 mouse button(s) to listen for. See
param
action- The function that is run when certain mouse buttons are being held down.
// count time with left mouse button down
let mouseTime = 0;
onMouseDown("left", () => {
mouseTime += dt();
debug.log(`Time with mouse down: ${mouseTime});
});
returns
The event controller.
since
v3001.0
group
Input
subgroup
Mouse
Function
(action: (m: MouseButton) => void): KEventController Register an event that runs every frame when any mouse button is being held down.
param
action- The function that is run when any mouse button is being held down.
// count time with any mouse button down
let mouseTime = 0;
onMouseDown((m) => {
mouseTime += dt();
});
returns
The event controller.
since
v3001.0
group
Input
subgroup
Mouse
Function
(action: (m: MouseButton) => void): KEventController Register an event that runs when user clicks mouse.
param
action- The function that is run when user clicks a mouse button.
// gives cookies on left press, remove on right press
let cookies = 0;
onMousePress(["left", "right"], (m) => {
if (m == "left") {
cookies++;
} else {
cookies--;
}
});
returns
The event controller.
since
v3001.0
group
Input
subgroup
Mouse
Function
(btn: MouseButton | MouseButton[], action: (m: MouseButton) => void): KEventController Register an event that runs when user clicks mouse.
param
btn- The mouse button(s) to listen for. See
param
action- The function that is run what the user clicks cetain mouse buttons.
// gives cookies on any mouse press
let cookies = 0;
onMousePress((m) => {
cookies++;
debug.log(`Cookies: ${cookies}`);
});
returns
The event controller.
since
v3001.0
group
Input
subgroup
Mouse
Function
(action: (m: MouseButton) => void): KEventController Register an event that runs when user releases mouse.
param
action- The function that is run what the user clicks a provided mouse button.
// spawn bean where right mouse is released
onMouseRelease("right", (m) => {
debug.log(`${m} released, spawning bean...`);
add([
pos(mousePos()),
sprite("bean"),
anchor("center"),
]);
});
returns
The event controller.
since
v3001.0
group
Input
subgroup
Mouse
Function
(btn: MouseButton | MouseButton[], action: (m: MouseButton) => void): KEventController Register an event that runs when user releases mouse.
param
btn- The button(s) to listen for. See
param
action- The function that is run what the user clicks a provided mouse button.
// spawn bean where right mouse is released
onMouseRelease((m) => {
if (m == "right") {
debug.log(`${m} released, spawning bean...`);
add([
pos(mousePos()),
sprite("bean"),
anchor("center"),
]);
});
});
returns
The event controller.
since
v3001.0
group
Input
subgroup
Mouse
Function
(action: (pos: Vec2, delta: Vec2) => void): KEventController Register an event that runs whenever user moves the mouse.
param
action- The function that is run what the user moves the mouse.
// runs when the mouse has moved
onMouseMove((p, d) => {
bean.pos = p; // set bean position to mouse position
});
returns
The event controller.
since
v2000.1
group
Input
subgroup
Mouse
Function
(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
subgroup
Touch
Function
(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
subgroup
Touch
Function
(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
subgroup
Touch
Function
(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
subgroup
Mouse
Function
(action: (gamepad: KGamepad) => void): KEventController Register an event that runs when a gamepad is connected.
param
action- The function that runs when quit() is called.
// watch for a controller connecting
onGamepadConnect((gp) => {
debug.log(`ohhi player ${gp.index + 1}`);
});
returns
The event controller.
since
v3000.0
group
Input
subgroup
Gamepad
Function
(action: (gamepad: KGamepad) => void): KEventController Register an event that runs when a gamepad is disconnected.
param
action- The function that runs when quit() is called.
// watch for a controller disconnecting
onGamepadDisconnect((gp) => {
debug.log(`ohbye player ${gp.index + 1}`);
});
returns
The event controller.
since
v3000.0
group
Input
subgroup
Gamepad
Function
(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. See
param
action- The function that is run while certain gamepad buttons are held down.
// when button is being held down
onGamepadButtonDown("rtrigger", (gp) => {
car.addForce(Vec2.fromAngle(car.angle).scale(10));
});
returns
The event controller.
since
v3001.0
group
Input
subgroup
Gamepad
Function
(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 that is run while any gamepad buttons are held down.
// when button is being held down
onGamepadButtonDown((btn, gp) => {
if (btn == "rtrigger") {
car.addForce(Vec2.fromAngle(car.angle).scale(10));
} else if (btn == "ltrigger") {
car.addForce(Vec2.fromAngle(car.angle).scale(-5));
}
});
returns
The event controller.
since
v3001.0
group
Input
subgroup
Gamepad
Function
(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. See
param
action- The function that is run when certain gamepad buttons are pressed.
// when user presses button
onGamepadButtonPress("south", (btn, gp) => {
player.jump(200);
});
returns
The event controller.
since
v3001.0
group
Input
subgroup
Gamepad
Function
(action: (btn: KGamepadButton, gamepad: KGamepad) => void): KEventController Register an event that runs when user presses any gamepad button.
param
action- The function that is run when any gamepad buttons is pressed.
// when user presses button
onGamepadButtonPress((btn, gp) => {
if (btn == "south") {
player.jump(200); // jump
}
});
returns
The event controller.
since
v3001.0
group
Input
subgroup
Gamepad
Function
(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. See
param
action- The function that is run when certain gamepad buttons are released.
// charged attack
let chargeTime = 0
onGamepadButtonPress("west", (btn, gp) => {
chargeTime = time();
});
// when a gamepad button is released, this is run
onGamepadButtonRelease("west", (btn, gp) => {
let chargedt = time() - chargeTime;
debug.log(`Used ${chargedt * 1000} power!`);
});
returns
The event controller.
since
v3001.0
group
Input
subgroup
Gamepad
Function
(action: (btn: KGamepadButton, gamepad: KGamepad) => void): KEventController Register an event that runs when user releases any gamepad button.
param
action- The function that is run when any gamepad buttons are released.
// when a gamepad button is released, this is run
onGamepadButtonRelease((btn, gp) => {
if (btn == "north") {
player.jump(500);
}
});
returns
The event controller.
since
v3000.0
group
Input
subgroup
Gamepad
Function
(stick: KGamepadStick, action: (value: Vec2, gameepad: KGamepad) => void): KEventController Register an event that runs when the gamepad axis exists.
param
stick- The stick to listen for. See
param
action- The function that is run when a specific gamepad stick is moved.
// player move
let player = add([
pos(center()),
sprite(`bean`),
]);
// when left stick is moved
onGamepadStick("left", (stickVector, gp) => {
player.move(stickVector.x, 0);
});
returns
The event controller.
since
v3000.0
group
Input
subgroup
Gamepad
Function
(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
subgroup
Buttons API
Function
(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
subgroup
Buttons API
Function
(action: (btn: TButton) => void): KEventController Function
(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
subgroup
Buttons API
Function
(action: (btn: TButton) => void): KEventController Function
(): boolean Is currently on a touch screen device.
returns
true if on a touch screen device.
since
v3000.0
group
Input
subgroup
Touch
Function
(): Vec2 Get current mouse position (without camera transform).
returns
The current mouse position.
since
v2000.0
group
Input
subgroup
Mouse
Function
(): Vec2 How much mouse moved last frame.
returns
The delta mouse position.
since
v2000.0
group
Input
subgroup
Mouse
Function
(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
subgroup
Keyboard
Function
(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
subgroup
Keyboard
Function
(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
subgroup
Keyboard
Function
(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
subgroup
Keyboard
Function
(btn?: MouseButton | MouseButton[]): boolean If mouse buttons are currently down.
param
btn- The button(s) to check.
since
v2000.0
group
Input
subgroup
Mouse
Function
(btn?: MouseButton | MouseButton[]): boolean If mouse buttons are just clicked last frame
param
btn- The button(s) to check.
since
v2000.0
group
Input
subgroup
Mouse
Function
(btn?: MouseButton | MouseButton[]): boolean If mouse buttons are just released last frame.
param
btn- The button(s) to check.
since
v2000.0
group
Input
subgroup
Mouse
Function
(): boolean If mouse moved last frame.
since
v2000.1
group
Input
subgroup
Mouse
Function
(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
subgroup
Gamepad
Function
(btn?: KGamepadButton | KGamepadButton): boolean If certain gamepad buttons are currently held down.
param
btn- The button(s) to check.
since
v3000.0
group
Input
subgroup
Gamepad
Function
(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
subgroup
Gamepad
Function
(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
subgroup
Buttons API
Function
(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
subgroup
Buttons API
Function
(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
subgroup
Buttons API
Function
(btn: keyof TButtonDef): ButtonBinding Get a input binding from a button name.
param
btn- The button to get binding for.
since
v3001.0
group
Input
subgroup
Buttons API
Function
(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
subgroup
Buttons API
Function
(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
subgroup
Buttons API
Function
(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
subgroup
Buttons API
Function
(stick: KGamepadStick): 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
subgroup
Gamepad
Function
(): 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
subgroup
Util
Function
(): string[] List of characters inputted since last frame.
returns
An array of characters inputted.
since
v3000.0
group
Input
subgroup
Keyboard
Type
: { ?: KGamepadButton | KGamepadButton[] ?: MouseButton | MouseButton[] } A button binding.
group
Input
subgroup
Buttons API
Type
: Record<string, ButtonBinding> A buttons definition for an action (jump, walk-left, run).
group
Input
subgroup
Buttons API
Type
: "keyboard" | "gamepad" | "mouse" A button binding device
group
Input
subgroup
Buttons API
Type
: ("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
subgroup
Keyboard
Type
: "left" | "right" | "middle" | "back" | "forward" A mouse button.
group
Input
subgroup
Mouse
Type
: "north" | "east" | "south" | "west" | "ltrigger" | "rtrigger" | "lshoulder" | "rshoulder" | "select" | "start" | "lstick" | "rstick" | "dpad-up" | "dpad-right" | "dpad-down" | "dpad-left" | "home" | "capture" | "touchpad" A gamepad button.
group
Input
subgroup
Gamepad
Type
: "left" | "right" A gamepad stick.
group
Input
subgroup
Gamepad
Type
: { : Record<string, KGamepadButton> : Partial<Record<KGamepadStick, {}>> } A gamepad definition. Used in KAPLAYOpt
group
Input
subgroup
Gamepad
Type
: { : number The order of the gamepad in the gamepad list.
(b: KGamepadButton): boolean If certain button is pressed.
(b: KGamepadButton): boolean If certain button is held down.
(b: KGamepadButton): boolean If certain button is released.
(stick: KGamepadStick): Vec2 Get the value of a stick.
} A KAPLAY gamepad
group
Input
subgroup
Gamepad
Function
(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
Function
(event: Ev, tag: Tag, action: (obj: GameObj, args: TupleWithoutFirst<GameObjEvents[Ev]>) => 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
Function
(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
Function
(tag: Tag, action: (obj: GameObj) => void): KEventController Function
(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
Function
(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
Function
(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
Function
(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
Function
(tag: Tag, action: (obj: GameObj) => void): KEventController Register an event that runs when an object with the provided tag is added.
param
tag- The tag to listen for.
param
action- The function that runs when an object is added.
// This will run when the object is added.
onAdd("player", () => {
debug.log("ohhi");
});
add([
pos(),
"player"
]);
returns
The event controller.
since
v2000.0
group
Events
Function
(action: (obj: GameObj) => void): KEventController Register an event that runs when an object is added
param
action- The tag to match, only called for objects with a matching tag.
param
unknown- The function that runs when an object is added.
// This will run when the object is added.
onAdd(() => {
debug.log("ohhi");
});
add([
pos(),
]);
returns
The event controller.
since
v2000.0
group
Events
Function
(tag: Tag, action: (obj: GameObj) => void): KEventController Register an event that runs when an object with the provided tag is destroyed.
param
tag- The function that runs when an object is destroyed.
// This will run when the tagged object is destroyed.
onDestroy("bean", () => {
debug.log("ohbye");
});
let player = add([
pos(),
"bean"
])
// Destroy the tagged object
destroy(player);
returns
The event controller.
since
v2000.0
group
Events
Function
(action: (obj: GameObj) => void): KEventController Register an event that runs when an object is destroyed.
param
action- The tag to match, only called for objects with a matching tag.
param
unknown- The function that runs when an object is destroyed.
// This will run when the object is destroyed.
onDestroy(() => {
debug.log("ohbye");
});
let ghosty = add([
pos(),
]);
// Destroy the object
destroy(ghosty);
returns
The event controller.
group
Events
Function
(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.1
group
Events
Function
(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.1
group
Events
Function
(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.1
group
Events
Function
(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.1
group
Events
Function
(action: () => void): KEventController | undefined 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
Function
(action: (name: string, failedAsset: Asset<any>) => void): KEventController | undefined Register an event that runs once for each asset that failed to load,
after all others have completed.
param
action- The 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
Function
(action: (progress: number) => void): KEventController 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 that runs when assets are loading.
```
// progress bar
onLoading((progress) => {
// Background of the bar
drawRect({
width: 240,
height: 40,
pos: center().add(-120,0),
color: BLACK,
anchor: `left,
});
// Progress of the bar
drawRect({
width: map(progress, 0, 1, 0, 220),
height: 32,
pos: center().add(-116, 0),
color: BLUE,
anchor: `left
});
});
returns
The event controller.
since
v3000.0
group
Events
Function
(action: (err: Error) => void): KEventController Register a custom error handler. Can be used to draw a custom error screen.
param
action- The function that runs when the program errors.
// Create custom error handler
onError((err) => {
drawRect({
width: width(),
height: height(),
pos: center(),
color: RED,
anchor: `center,
});
drawText({
text: err.message,
size: 48,
width: width()/2,
anchor: `center`,
align: `center`,
pos: center(),
color: BLACK
});
});
// cause common error
let pos = add([
pos()
]);
returns
The event controller.
since
v3000.0
group
Events
Function
(action: () => void): KEventController Register an event that runs when the canvas resizes.
param
action- The function that runs when the canvas resizes.
// create a rectangle with screen size
let rectangle = add([
rect(width(), height()),
color(GREEN),
]);
// resize the rectangle to screen size
onResize(() => {
debug.log(`Old Size: ${rectangle.width}x${rectangle.height}`);
rectangle.width = width();
rectangle.height = height();
debug.log(`New Size: ${rectangle.width}x${rectangle.height}`);
});
returns
The event controller.
since
v3000.0
group
Events
Function
(action: () => void): void Cleanup function to run when quit() is called.
param
action- The function that runs when quit() is called.
// useful externally from KAPLAY
onCleanup(() => {
console.log(`ohbye :(`);
});
quit();
returns
The event controller.
since
v3000.0
group
Events
Function
(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
Function
(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
Function
(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
Events
Function
(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
Function
(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
Function
(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
Function
(action: () => void): KEventController Register an event that runs when tab is hidden.
param
action- The function that is run what the tab is hidden.
// spooky ghost
let ghosty = add([
pos(center()),
sprite("ghosty"),
anchor("center"),
]);
// when switching tabs, this runs
onHide(() => {
destroy(ghosty);
add([
text("There was never aa ghosttttt"),
pos(center()),
anchor("center")
]);
});
returns
The event controller.
since
v3001.0
group
Events
Function
(action: () => void): KEventController Register an event that runs when tab is shown.
param
action- The function that is run when the tab is shown.
// user has returned to this tab
onShow(() => {
burp();
});
returns
The event controller.
since
v3001.0
group
Events
Function
(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
Class
: (action: (args: Args) => unknown)
=> KEventController (action: (args: (Args | PromiseLike<Args>)[]) => void)
=> KEventController Class
: : Partial<{
[Name in
keyof EventMap]:
Registry< (args: EventMap[Name]) => void> } > (name: Name, action: (args: EventMap[Name]) => void)
=> KEventController (name: Name, action: (args: EventMap[Name]) => void)
=> KEventController (name: Name)
=> Promise<unknown> (name: Name, args: EventMap[Name])
=> void Class
: 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
: boolean If the event is paused
: () => void Cancel the event
static (events: KEventController[])
=> KEventController static (oldEv: KEventController, newEv: KEventController)
=> KEventController Constant
: () => Symbol Cancels the event by returning the cancel symbol.
onKeyPress((key) => {
if (key === "q") return cancel();
});
returns
The cancel event symbol.
since
v4000.0
group
Events
Class
: Type
: { : [GameObj] Triggered every frame
: [GameObj] Triggered every frame at a fixed 50fps rate
: [GameObj] Triggered every frame before update
: [GameObj] Triggered when object is added
: [GameObj] Triggered when object is destroyed
: [GameObj, string] Triggered when component is used
: [GameObj, string] Triggered when component is unused
: [GameObj, string] Triggered when tag is added
: [GameObj, string] Triggered when tag is removed
: [GameObj, GameObj, Collision] Triggered when object collides with another object
From area component
: [GameObj, GameObj, Collision] Triggered every frame when object collides with another object
From area component
: [GameObj, GameObj, Collision] Triggered when object stops colliding with another object
From area component
: [GameObj,
Parsing error with NamedTupleMember
] Triggered when object is hurted
From health component
: [GameObj,
Parsing error with NamedTupleMember
] Triggered when object is healed
From health component
: [GameObj] Triggered when object dies
From health component
: [GameObj,
Parsing error with NamedTupleMember
] Triggered before physics resolves
From body component
: [GameObj,
Parsing error with NamedTupleMember
] Triggered after physics resolves
From body component
: [GameObj] Triggered when object is on the ground
From body component
: [GameObj] Triggered when object is falling
From body component
: [GameObj] Triggered when object stops falling
From body component
: [GameObj] Triggered when object head butt something (like Mario with brick)
From body component
: [GameObj] Triggered when an object lands on this object
From body component
: [GameObj] Triggered when object is headbutted by another object
From body component
: [GameObj] Triggered when object double jumps
From doubleJump component
: [GameObj] Triggered when object goes out of view
From offscreen component
: [GameObj] Triggered when object enters view
From offscreen component
: [GameObj,
Parsing error with NamedTupleMember
] Triggered when a sprite animation starts
From sprite component
: [GameObj,
Parsing error with NamedTupleMember
] Triggered when a sprite animation ends
From sprite component
: [GameObj, GameObj, Vec2] From agent component
: [GameObj, GameObj] From agent component
: [GameObj, GameObj] From agent component
: [GameObj, GameObj] From agent component
: [GameObj] From patrol component
: [GameObj, GameObj[]] From sentry component
: [GameObj,
Parsing error with NamedTupleMember
] From animate component
: [GameObj] From animate component
: [GameObj] From level of addLevel function
: [GameObj] From level of addLevel function
: [GameObj] From level of addLevel function
} Game Object events with their arguments.
If looking for use it with obj.on()
, ignore first parameter (Game Obj)
group
Events
subgroup
Game Obj
Type
: GameObjEventMap & {} group
Events
subgroup
Game Obj
Type
: keyof GameObjEventMap group
Events
subgroup
Game Obj
Type
: { : [KGamepadButton, KGamepad] : [KGamepadButton, KGamepad] : [KGamepadButton, KGamepad] : [string, Vec2, KGamepad] } App events with their arguments
Type
: {} All Game State events with their arguments
Function
(): number Get the width of game.
returns
The width of the game.
since
v2000.0
group
Info
Function
(): number Get the height of game.
returns
The height of the game.
since
v2000.0
group
Info
Function
(): 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
Function
(): 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
Function
(): number Get the fixed delta time since last frame.
Function
(): number Get the rest delta time since last frame.
Function
(): number Get the total time since beginning.
Function
(): boolean If the game canvas is currently focused.
returns
true if focused.
since
v2000.1
group
Info
Function
(color: Color): void Set background color.
Function
(color: Color, alpha: number): void Function
(r: number, g: number, b: number): void Function
(r: number, g: number, b: number, alpha: number): void Function
(): Color | null Get background color.
returns
The background color.
since
v3000.0
group
Info
Function
(): KGamepad[] Get connected gamepads.
returns
An array of connected gamepads.
since
v3000.0
group
Info
Function
(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
Function
(): Cursor Get current cursor style.
returns
The current cursor style.
since
v2000.0
group
Info
Function
(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.
Function
(): boolean Get if cursor is currently locked.
returns
true if locked, false otherwise.
since
v2000.0
group
Info
Function
(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
Function
(): boolean If currently in fullscreen mode.
returns
true if fullscreen, false otherwise.
since
v2000.0
group
Info
Constant
: HTMLCanvasElement The canvas DOM KAPLAY is currently using.
Constant
: string Current KAPLAY library version.
Function
(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
Function
(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
Interface
: : number The time left for the callback to be called.
: boolean If the event handler is paused.
(): void Cancel the event handler.
(action: () => void): void Register an event when finished.
(action: () => void): TimerController Interface
: Event controller for tween.
: number The current time in the duration of the tween
(): void Finish the tween now and cancel.
Function
(origin: Vec2, direction: Vec2, exclude?: string[]): RaycastResult Create a raycast.
since
v3001.0
group
Math
subgroup
Raycast
Function
(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
Math
subgroup
Random
Function
(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
Math
subgroup
Random
Function
(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
Math
subgroup
Random
Function
(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
Function
(p: Vec2): Vec2 Function
(xy: number): Vec2 Function
(): Vec2 Function
(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
Function
(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
Function
(cssColor: CSSColor): Color Create a color from CSS name.
param
cssColor- The CSS name.
sea.color = rgb("slateblue");
returns
The color.
since
v3001.0.10
experimental
This feature is in experimental phase, it will be fully released in v3001.1.0
Function
(): Color Same as rgb(255, 255, 255).
Function
(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
subgroup
Colors
Function
(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
subgroup
Advanced
Function
(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
Math
subgroup
Random
Function
(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
Math
subgroup
Random
Function
(lst: T[]): T[] Shuffle an array.
param
lst- The list to shuffle.
returns
A shuffled array.
since
v3001.0
group
Math
subgroup
Random
Function
(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
subgroup
Random
Function
(from: V, to: V, t: number): V Linear interpolation. Can take a number, vector, or color.
Function
(from: V, to: V, duration: number, setValue: (value: V) => void, easeFunc?: (t: number) => number): TweenController Tweeeeeeeening!
// tween bean to mouse position
tween(bean.pos, mousePos(), 1, (p) => bean.pos = p, easings.easeOutBounce)
since
v3000.0
group
Math
subgroup
Tween
Constant
: Record<EaseFuncs, EaseFunc> A collection of easing functions for tweening.
since
v3000.0
group
Math
subgroup
Tween
Function
(steps: number, position: StepPosition): (x: number) => number Steps easing. Eases in discontinious steps.
since
v3001.0
group
Math
subgroup
Tween
Function
(keys: Vec2[]): (x: number) => number Linear easing with keyframes.
since
v3001.0
group
Math
subgroup
Tween
Function
(p1: Vec2, p2: Vec2): (x: number) => number Bezier easing. Both control points need x to be within 0 and 1.
since
v3001.0
group
Math
subgroup
Tween
Function
(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
v- The value the function will depend on.
param
l1- The minimum value of the source range.
param
h1- The minimum result value.
param
l2- The maximum value of the source range.
param
h2- The 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
Function
(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
v- The value the function will depend on.
param
l1- The minimum value of the source range.
param
h1- The minimum result value.
param
l2- The maximum value of the source range.
param
h2- The 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
Function
(lo: V, hi: V, t: number, func?: (x: number) => number): V Interpolate back and forth between 2 values.
(Optionally takes a custom periodic function, which default to a sine wave.).
// 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
Function
(deg: number): number Convert degrees to radians.
Function
(rad: number): number Convert radians to degrees.
Function
(n: number, min: number, max: number): number Return a value clamped to an inclusive range of min and max.
Function
(pt1: Vec2, pt2: Vec2, pt3: Vec2, t: number): Vec2 Evaluate the quadratic Bezier at the given t.
group
Math
subgroup
Advanced
Function
(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
subgroup
Advanced
Function
(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
subgroup
Advanced
Function
(pt1: Vec2, pt2: Vec2, pt3: Vec2, pt4: Vec2, t: number): Vec2 Evaluate the cubic Bezier at the given t.
since
v3001.0
group
Math
subgroup
Advanced
Function
(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
subgroup
Advanced
Function
(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
subgroup
Advanced
Function
(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
subgroup
Advanced
Function
(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
subgroup
Advanced
Function
(curve: (t: number) => Vec2, entries: number, detail: number): (t: number, inverse: boolean) => 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
subgroup
Advanced
Function
(curve: (t: number) => Vec2): (s: number) => 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
subgroup
Advanced
Function
(pt1: number, m1: number, m2: number, pt2: number): (t: number) => number A second order function returning an evaluator for the given 1D Hermite curve.
param
pt1- First point.
param
m1- First control point (tangent).
param
m2- Second control point (tangent).
param
pt2- Second point.
returns
A function which gives the value on the 1D Hermite curve at t.
group
Math
subgroup
Advanced
Function
(pt1: Vec2, m1: Vec2, m2: Vec2, pt2: Vec2, tension: number): (t: number) => Vec2 A second order function returning an evaluator for the given 2D Cardinal curve.
param
pt1- Previous point.
param
m1- First point.
param
m2- Second point.
param
pt2- Next point.
param
tension- The tension of the curve, [0..1] from round to tight.
returns
A function which gives the value on the 2D Cardinal curve at t.
group
Math
subgroup
Advanced
Function
(pt1: Vec2, m1: Vec2, m2: Vec2, pt2: Vec2): (t: number) => Vec2 A second order function returning an evaluator for the given 2D Catmull-Rom curve.
param
pt1- Previous point.
param
m1- First point.
param
m2- Second point.
param
pt2- Next point.
returns
A function which gives the value on the 2D Catmull-Rom curve at t.
group
Math
subgroup
Advanced
Function
(pt1: Vec2, pt2: Vec2, pt3: Vec2, pt4: Vec2): (t: number) => Vec2 A second order function returning an evaluator for the given 2D quadratic Bezier curve.
param
pt1- First point.
param
pt2- First control point.
param
pt3- Second control point.
param
pt4- Second point.
returns
A function which gives the value on the 2D quadratic Bezier curve at t.
group
Math
subgroup
Advanced
Function
(pt1: Vec2, pt2: Vec2, pt3: Vec2, pt4: Vec2, tension: number, continuity: number, bias: number): (t: number) => Vec2 A second order function returning an evaluator for the given 2D Kochanek–Bartels curve.
param
pt1- Previous point.
param
pt2- First point.
param
pt3- Second point.
param
pt4- Next point.
param
tension- The tension of the curve, [-1..1] from round to tight.
param
continuity- The continuity of the curve, [-1..1] from box corners to inverted corners.
param
bias- The bias of the curve, [-1..1] from pre-shoot to post-shoot.
returns
A function which gives the value on the 2D Kochanek–Bartels curve at t
group
Math
subgroup
Advanced
Function
(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
subgroup
Advanced
Function
(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.
returns
The intersection point, or null if the lines are parallel.
since
v2000.0
group
Math
subgroup
Advanced
Function
(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
subgroup
Advanced
Function
(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
subgroup
Advanced
Function
(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
subgroup
Advanced
Function
(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
subgroup
Advanced
Function
(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
subgroup
Advanced
Function
(r: Rect, l: Line, result: Line): boolean since
v4000.0
group
Math
subgroup
Advanced
Function
(c: Circle, l: Line, result: Line): boolean since
v4000.0
group
Math
subgroup
Advanced
Constant
: typeof anchorPt Returns a vector representing the anchor coordinates relative to the object's half-width, half-height, and center.
For example: anchorToVec2("right")
returns vec2(1, 0)
, which means
the anchor is fully to the right horizontally (1), and in-line with the
centerpoint vertically (0).
Or, anchorToVec2("botleft")
returns vec2(-1, 1)
, which means fully to the
left (-1), and fully to the bottom (1).
since
v4000.0
group
Math
subgroup
Vectors
Function
(shapeA: Shape, shapeB: Shape): boolean since
v4000.0
group
Math
subgroup
Advanced
Function
(shapeA: Shape, shapeB: Shape): GjkCollisionResult | null since
v4000.0
group
Math
subgroup
Advanced
Function
(pts: Vec2[]): boolean returns
true if the given polygon is convex
since
v3001.0
group
Math
subgroup
Advanced
Function
(edge: number, x: number): number returns
1 if over the edge, 0 otherwise
since
v3001.0
group
Math
subgroup
Advanced
Function
(edge0: number, edge1: number, x: number): number returns
1 if over edge1, 0 if under edge0, a smooth hermite curve value otherwise
since
v3001.0
group
Math
subgroup
Advanced
Function
(pts: Vec2[]): Vec2[][] since
v3001.0
group
Math
subgroup
Advanced
Class
: (vertices: Vec2[])
=> NavPolygon (pos: Vec2, size: Vec2)
=> NavPolygon (index: number)
=> number[] (a: number, b: number)
=> number (indexA: number, indexB: number)
=> number (start: number, goal: number)
=> number[] (start: Vec2, goal: Vec2, opt: any)
=> Vec2[] Class
: (m: Mat23, s?: Shape)
=> Point (shape: ShapeType)
=> boolean (origin: Vec2, direction: Vec2)
=> RaycastResult (direction: Vec2)
=> Vec2 Class
: (m: Mat23, s?: Shape)
=> Line (shape: ShapeType | Vec2)
=> boolean (origin: Vec2, direction: Vec2)
=> RaycastResult (direction: Vec2)
=> Vec2 Class
: static (p1: Vec2, p2: Vec2)
=> Rect ()
=> [Vec2, Vec2, Vec2, Vec2] (m: Mat23, s?: Shape)
=> Polygon (shape: ShapeType | Vec2)
=> boolean (origin: Vec2, direction: Vec2)
=> RaycastResult (direction: Vec2)
=> Vec2 Class
: (tr: Mat23, s?: Shape)
=> Ellipse (shape: ShapeType | Vec2)
=> boolean (origin: Vec2, direction: Vec2)
=> RaycastResult (direction: Vec2)
=> Vec2 Class
: static (tr: Mat2)
=> Ellipse (shape: ShapeType)
=> boolean (origin: Vec2, direction: Vec2)
=> RaycastResult (direction: Vec2)
=> Vec2 Class
: (m: Mat23, s?: Shape)
=> Polygon (shape: ShapeType | Vec2)
=> boolean (origin: Vec2, direction: Vec2)
=> RaycastResult (a: Vec2, b: Vec2, srcUv?: Vec2[], dstUv?: [Vec2[], Vec2[]])
=> [Polygon | null, Polygon | null] (direction: Vec2)
=> Vec2 Class
: A 2D vector.
: number The x coordinate
: number The y coordinate
(x: number, y: number)
=> Vec2 Set the X and Y of this vector
static (deg: number)
=> Vec2 Create a new Vec2 from an angle in degrees
static (arr: Array<number>)
=> Vec2 Create a new Vec2 from an array
static : Vec2 An empty vector. (0, 0)
static : Vec2 A vector with both components of 1. (1, 1)
static : Vec2 A vector signaling to the left. (-1, 0)
static : Vec2 A vector signaling to the right. (1, 0)
static : Vec2 A vector signaling up. (0, -1)
static : Vec2 A vector signaling down. (0, 1)
()
=> Vec2 Closest orthogonal direction: LEFT, RIGHT, UP, or DOWN
()
=> Vec2 Clone the vector
static (v: Vec2, out: Vec2)
=> Vec2 (args: Vec2Args)
=> Vec2 Returns the sum with another vector.
static (v: Vec2, other: Vec2, out: Vec2)
=> Vec2 Calculates the sum of the vectors
param
v- The first term
param
other- The second term
param
out- The vector sum
returns
The sum of the vectors
static (v: Vec2, other: Vec2, s: number, out: Vec2)
=> Vec2 static (v: Vec2, x: number, y: number, out: Vec2)
=> Vec2 Calculates the sum of the vectors
param
v- The first term
param
x- The x of the second term
param
y- The y of the second term
param
out- The vector sum
returns
The sum of the vectors
(args: Vec2Args)
=> Vec2 Returns the difference with another vector.
static (v: Vec2, other: Vec2, out: Vec2)
=> Vec2 Calculates the difference of the vectors
param
v- The first term
param
other- The second term
param
out- The vector difference
returns
The difference of the vectors
static (v: Vec2, x: number, y: number, out: Vec2)
=> Vec2 Calculates the difference of the vectors
param
v- The first term
param
x- The x of the second term
param
y- The y of the second term
param
out- The vector difference
returns
The difference of the vectors
(args: Vec2Args)
=> Vec2 Scale by another vector. or a single number
static (v: Vec2, s: number, out: Vec2)
=> Vec2 Calculates the scale of the vector
param
v- The vector
param
s- The x scale
param
out- The y scale
param
unknown- The scaled vector
returns
The scale of the vector
static (v: Vec2, x: number, y: number, out: Vec2)
=> Vec2 Calculates the scale of the vector
param
v- The vector
param
x- The x scale
param
y- The y scale
param
out- The scaled vector
returns
The scale of the vector
static (v: Vec2, other: Vec2, out: Vec2)
=> Vec2 Calculates the scale of the vector
param
v- The vector
param
other- The scale
param
out- The scaled vector
returns
The scale of the vector
(args: Vec2Args)
=> Vec2 Scale by the inverse of another vector. or a single number
(args: Vec2Args)
=> number Get distance between another vector
static (v: Vec2, other: Vec2)
=> number Calculates the distance between the vectors
param
v- The vector
param
other- The other vector
returns
The between the vectors
(args: Vec2Args)
=> number Get squared distance between another vector
static (v: Vec2, other: Vec2)
=> number Calculates the squared distance between the vectors
param
v- The vector
param
other- The other vector
returns
The distance between the vectors
()
=> number Get length of the vector
static (v: Vec2)
=> number Calculates the length of the vector
param
v- The vector
returns
The length of the vector
()
=> number Get squared length of the vector
static (v: Vec2)
=> number Calculates the squared length of the vector
param
v- The vector
returns
The squared length of the vector
()
=> Vec2 Get the unit vector (length of 1).
static (v: Vec2, out: Vec2)
=> Vec2 ()
=> Vec2 Get the perpendicular vector.
static (v: Vec2, out: Vec2)
=> Vec2 (normal: Vec2)
=> Vec2 Get the reflection of a vector with a normal.
(on: Vec2)
=> Vec2 Get the projection of a vector onto another vector.
(on: Vec2)
=> Vec2 Get the rejection of a vector onto another vector.
(vecOrAngle: Vec2 | number)
=> Vec2 static (v: Vec2, dir: Vec2, out: Vec2)
=> Vec2 Calculates the rotated vector
param
v- The vector
param
dir- The rotation vector
param
out- The rotated vector
returns
The rotated vector
static (v: Vec2, angle: number, out: Vec2)
=> Vec2 Calculates the rotated vector
param
v- The vector
param
angle- The angle in radians
param
out- The rotated vector
returns
The rotated vector
(vecOrAngle: Vec2 | number)
=> Vec2 static (v: Vec2, dir: Vec2, out: Vec2)
=> Vec2 Calculates the inverse rotated vector
param
v- The vector
param
dir- The rotation vector
param
out- The rotated vector
returns
The rotated vector
(p2: Vec2)
=> number Get the dot product with another vector.
static (v: Vec2, other: Vec2)
=> number Get the dot product between 2 vectors.
(p2: Vec2)
=> number Get the cross product with another vector.
static (v: Vec2, other: Vec2)
=> number Get the cross product between 2 vectors.
(args: Vec2Args)
=> number Get the angle of the vector in degrees.
static (v: Vec2)
=> number Calculates the angle represented by the vector in radians
param
v- The vector
returns
Angle represented by the vector in radians
(args: Vec2Args)
=> number Get the angle between this vector and another vector.
static (v: Vec2, other: Vec2)
=> number Calculates the angle between the vectors in radians
param
v- First vector
param
other- Second vector
returns
Angle between the vectors in radians
(dest: Vec2, t: number)
=> Vec2 Linear interpolate to a destination vector (for positions).
static (src: Vec2, dst: Vec2, t: number, out: Vec2)
=> Vec2 Linear interpolate src and dst by t
param
src- First vector
param
dst- Second vector
param
t- Percentage
param
out- The linear interpolation between src and dst by t
returns
The linear interpolation between src and dst by t
(dest: Vec2, t: number)
=> Vec2 Spherical linear interpolate to a destination vector (for rotations).
static (src: Vec2, dst: Vec2, t: number, out: Vec2)
=> Vec2 Spherical interpolate src and dst by t
param
src- First vector
param
dst- Second vector
param
t- Percentage
param
out- The spherical interpolation between src and dst by t
returns
The spherical interpolation between src and dst by t
()
=> boolean If the vector (x, y) is zero.
(n: number)
=> Vec2 To n precision floating point.
(m: Mat4)
=> Vec2 Multiply by a Mat4.
(other: Vec2)
=> boolean See if one vector is equal to another.
()
=> Rect Converts the vector to a Rect with the vector as the origin.
()
=> Array<number> Converts the vector to an array.
static (data: SerializedVec2)
=> Vec2 Class
: 0-255 RGBA color.
group
Math
subgroup
Colors
static (arr: [number, number, number])
=> Color static (hex: string | number)
=> Color Create color from hex string or literal.
Color.fromHex(0xfcef8d)
Color.fromHex("#5ba675")
Color.fromHex("d46eb3")
since
v3000.0
static (h: number, s: number, l: number)
=> Color static (cssColor: CSSColor)
=> Color Create a color from a CSS color name
param
cssColor- The color name.
loadHappy();
add([
rect(512, 512, {
radius: [0, 96, 96, 96]
}),
color("#663399"),
pos(40, 40),
]);
add([
text("css", { size: 192, font: "happy" }),
pos(90, 310)
]);
static
returns
The color.
experimental
This feature is in experimental phase, it will be fully released in v3001.1.0
(a: number)
=> Color Lighten the color (adds RGB by n).
(a: number)
=> Color Darkens the color (subtracts RGB by n).
(dest: Color, t: number)
=> Color Linear interpolate to a destination color.
()
=> [number, number, number] Convert color into HSL format.
(other: Color)
=> boolean ()
=> string Return the hex string of color.
()
=> Array<number> Return the color converted to an array.
static (data: {})
=> Color Class
: static (a: number)
=> Mat4 static (a: number)
=> Mat4 static (a: number)
=> Mat4 Class
: static (m: Mat2)
=> Mat23 static (t: Vec2)
=> Mat23 static (radians: number)
=> Mat23 static (s: Vec2)
=> Mat23 (x: number, y: number)
=> Mat23 (degrees: number)
=> Mat23 (x: number, y: number)
=> Mat23 (p: Vec2, o: Vec2)
=> Vec2 (v: Vec2, o: Vec2)
=> Vec2 (x: number, y: number, o: Vec2)
=> Vec2 (x: number, y: number, o: Vec2)
=> Vec2 Class
: group
Math
subgroup
Advanced
Class
: A random number generator using the linear congruential generator algorithm.
group
Math
subgroup
Random
: number The current seed value used by the random number generator.
()
=> number Generate a random number between 0 and 1.
const rng = new RNG(Date.now())
const value = rng.gen() // Returns number between 0-1
returns
A number between 0 and 1.
(a: number, b: number)
=> number Generate a random number between two values.
param
a- The minimum value.
param
b- The maximum value.
const rng = new RNG(Date.now())
const value = rng.genNumber(10, 20) // Returns number between 10-20
returns
A number between a and b.
(a: Vec2, b: Vec2)
=> Vec2 Generate a random 2D vector between two vectors.
param
a- The minimum vector.
param
b- The maximum vector.
const rng = new RNG(Date.now())
const vec = rng.genVec2(vec2(0,0), vec2(100,100))
returns
A vector between vectors a and b.
(a: Color, b: Color)
=> Color Generate a random color between two colors.
param
a- The first color.
param
b- The second color.
const rng = new RNG(Date.now())
const color = rng.genColor(rgb(0,0,0), rgb(255,255,255))
returns
A color between colors a and b.
(args: [] | [T] | [T, T])
=> T Generate a random value of a specific type.
param
args- No args for [0-1], one arg for [0-arg], or two args for [arg1-arg2].
const rng = new RNG(Date.now())
const val = rng.genAny(0, 100) // Number between 0-100
const vec = rng.genAny(vec2(0,0), vec2(100,100)) // Vec2
const col = rng.genAny(rgb(0,0,0), rgb(255,255,255)) // Color
returns
A random value.
Function
(array: T[], compare: (left: T, right: T) => boolean): void Sorts the array in-place using https.
This is useful when you have a persistent (not per-frame) array of objects and they change
on each frame but not by much, but the list must remain sorted. (For example, the list could
be returned by get with the `liveUpdate` option enabled, and then stored somewhere.)
param
array- returns true if `[left, right]` is the correct order, false if `[right, left]` is the correct order.
since
v4000.0
group
Math
subgroup
Advanced
Type
: [number, number, number] group
Math
subgroup
Colors
Type
: [number, number, number, number] group
Math
subgroup
Colors
Type
: keyof typeof CSS_COLOR_MAP group
Math
subgroup
Colors
Type
: [Color] | [Color, number] | RGBValue | RGBAValue | [string] | [number[]] | [] | [ CSSColor & ( string & {})] Possible color arguments for various functions.
group
Math
subgroup
Colors
Type
: number | Vec2 | Color A valid value for lerp.
Type
: [number, number] | [number] | [Vec2] | [number | Vec2] | [] Possible arguments for a Vec2.
group
Math
subgroup
Vectors
Class
: group
Math
subgroup
Advanced
(e1: number, e2: number)
=> number[][] static (radians: number)
=> Mat2 static (x: number, y: number)
=> Mat2 Type
: Point | Circle | Line | Rect | Polygon | Ellipse group
Math
subgroup
Shapes
Type
: {} group
Math
subgroup
Raycast
Type
: RaycastHit | null group
Math
subgroup
Raycast
Type
: "jump-start" | "jump-end" | "jump-none" | "jump-both" Type
: "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.
Type
: (t: number) => number A function that takes a time value and returns a new time value.
Type
: number | Vec2 | Color group
Math
subgroup
Random
Type
: "left" | "right" | "top" | "bottom" group
Math
subgroup
Advanced
Class
: A 3D vector.
group
Math
subgroup
Vectors
Function
(): string | null Gets the name of the current scene. Returns null if no scene is active.
since
v3001.0
group
Scenes
Function
(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
Scenes
Function
(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
Scenes
Function
(id: SceneName, args: unknown[]): void Push the current active scene to a stack and enters in the new scene
param
id- The scene name.
param
args- The args passed to the scene defition.
add([
text("this is the first scene", {size: 32 }),
pos(center()),
]);
scene("main", () => {
add([
sprite("bean"),
pos(center()),
]);
});
pushScene("main")
since
v3001.1
group
Scenes
Function
(id: SceneName, args: unknown[]): void Pops the scene from the stack and set as current active scene.
add([
text("this is the first scene", {size: 32 }),
pos(center()),
]);
scene("main", () => {
add([
sprite("bean"),
pos(center()),
]);
});
go("mainScene");
popScene(); // when triggered the text should appear on the center screen //
since
v3001.1
group
Scenes
Type
: string The name of a scene.
group
Scenes
subgroup
Types
Type
: (args: any) => void The function definition for a scene
group
Scenes
subgroup
Types
Type
: {} The state of a scene.
group
Scenes
subgroup
Types
Function
(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.1
group
Rendering
subgroup
Camera
Function
(x: number, y: number): void Function
(xy: number): void Function
(): Vec2 Get camera position.
returns
The current camera position.
since
v3001.1
group
Rendering
subgroup
Camera
Function
(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.1
group
Rendering
subgroup
Camera
Function
(x: number, y: number): void Function
(xy: number): void Function
(): Vec2 Get camera scale.
returns
The current camera scale.
since
v3001.1
group
Rendering
subgroup
Camera
Function
(angle: number): void Set camera rotation.
param
angle- The angle to rotate the camera.
// rotate camera 90 degrees
setCamRot(90);
since
v3001.1
group
Rendering
subgroup
Camera
Function
(): number Get camera rotation.
returns
The current camera rotation.
since
v3001.1
group
Rendering
subgroup
Camera
Function
(): Mat23 Get camera transform.
returns
The current camera transform.
since
v3001.1
group
Rendering
subgroup
Camera
Function
(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
Rendering
subgroup
Camera
Function
(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
Rendering
subgroup
Camera
Function
(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
Rendering
subgroup
Camera
Function
(x: number, y: number): Vec2 Function
(xy: number): Vec2 Function
(): Vec2 Function
(scale: Vec2): Vec2 param
scale- The scale to set the camera to.
deprecated
Use
returns
The current camera scale.
since
v2000.0
group
Rendering
subgroup
Camera
Function
(x: number, y: number): Vec2 Function
(xy: number): Vec2 Function
(): Vec2 Function
(angle?: number): number param
angle- The angle to rotate the camera.
deprecated
Use
returns
The current camera rotation.
since
v2000.0
group
Rendering
subgroup
Camera
Function
(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
onClick(() => {
// flashed
camFlash(WHITE, 0.5)
})
returns
A timer controller.
since
v3001.0
group
Rendering
subgroup
Camera
Function
(): Mat23 deprecated
use
group
Rendering
subgroup
Camera
Function
(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
Rendering
subgroup
Camera
Function
(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
Rendering
subgroup
Camera
Function
(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.1
group
Rendering
subgroup
Layers
Function
(): string[] | null Get the layer names.
returns
The layer names or null if not set.
since
v3001.1
group
Rendering
subgroup
Layers
experimental
This feature is in experimental phase, it will be fully released in v3001.1
Function
(): string | null Get the default layer name.
returns
The default layer name or null if not set.
since
v3001.0.5
group
Rendering
subgroup
Layers
experimental
This feature is in experimental phase, it will be fully released in v3001.1
Function
(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
Rendering
subgroup
Layers
Function
(): 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
Rendering
subgroup
Stack
Function
(): void Pop the topmost transform matrix from the transform stack.
since
v2000.0
group
Rendering
subgroup
Stack
Function
(t?: Vec2): 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
Rendering
subgroup
Stack
Function
(s?: Vec2): void Scale all subsequent draws.
since
v2000.0
group
Rendering
subgroup
Stack
Function
(angle?: number): void Rotate all subsequent draws.
since
v2000.0
group
Rendering
subgroup
Stack
Function
(mat?: Mat23): void Apply a transform matrix, ignore all prior transforms.
since
v3000.0
group
Rendering
subgroup
Stack
Function
(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
Rendering
subgroup
Shaders
Function
(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
Rendering
subgroup
Text
Function
(text: any): StyledTextInfo Parses the text that has formatting tags, and returns the unstyled text
(the actual characters that will be displayed) as well as which styles are
active on each character.
since
v4000
group
Rendering
subgroup
Text
Function
(w: number, h: number): Canvas Create a canvas to draw stuff offscreen.
returns
The canvas object.
since
v3001.0
group
Rendering
subgroup
Canvas
Type
: number | Vec2 | Color | Mat4 | Mat23 | number[] | Vec2[] | Color[] Possible values for a shader Uniform.
group
Rendering
subgroup
Shaders
Type
: string Possible uniform value, basically any but "u_tex".
group
Rendering
subgroup
Shaders
Type
: Record<UniformKey, UniformValue> group
Rendering
subgroup
Shaders
Class
: A shader, yeah.
group
Rendering
subgroup
Shaders
(vert: string, frag: string, attribs: string[])
=> WebGLProgram (uniform: Uniform)
=> void Class
: group
Rendering
subgroup
Canvas
static (ctx: GfxCtx, img: ImageSource, opt?: TextureOpt)
=> Texture (img: ImageSource, x?: number, y?: number)
=> void ()
=> void Frees up texture memory. Call this once the texture is no longer being used to avoid memory leaks.
Type
: {}[] group
Rendering
subgroup
Shaders
Class
: group
Rendering
subgroup
Canvas
(primitive: GLenum, vertices: number[], indices: number[], shader: Shader, tex: (Texture | null) | undefined, uniform: (Uniform | null) | undefined, blend: BlendMode, width: number, height: number, fixed: boolean)
=> void (width: number, height: number)
=> void (blend: BlendMode)
=> void Class
: group
Rendering
subgroup
Shaders
(primitive?: GLenum, index?: GLuint, count?: GLuint)
=> void Type
: (idx: number, ch: string) => CharTransform A function that returns a character transform config. Useful if you're generating dynamic styles.
group
Rendering
subgroup
Text
Interface
: Describes how to transform each character.
group
Rendering
subgroup
Text
?: Vec2 Offset to apply to the position of the text character.
Shifts the character's position by the specified 2D vector.
?: 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.
?: number Increases the amount of degrees to rotate the text character.
?: Color Color transformation applied to the text character.
Multiplies the current color with this color.
?: 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).
?: 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.
?: string | FontData If the font for this character should be different from the default font
or the one specified in .
Because the font can't be composed like the other properties,
this will override the font even if is false.
?: boolean If true, characters that have a X scale that is not 1 won't have the bounding box stretched to fit the character,
and may end up overlapping with adjacent characters.
?: string A name for a shader that will be applied to this character only.
?: Uniform Values to use for the shader's uniform inputs.
If there is no shader set (by this character's transform or an entire-text
transform), this is not used.
Type
: "center" | "left" | "right" How the text should be aligned.
group
Rendering
subgroup
Text
Type
: {} group
Rendering
subgroup
Camera
Type
: {} Formatted text with info on how and where to render each character.
group
Rendering
subgroup
Text
Interface
: One formatted character.
group
Rendering
subgroup
Text
Type
: {} group
Rendering
subgroup
Text
Type
: { : Record<number, string[]> } group
Rendering
subgroup
Text
Class
: group
Rendering
subgroup
Canvas
(action: () => void)
=> void Type
: {} group
Rendering
subgroup
Canvas
Type
: { : FrameBuffer | Picture | null } group
Rendering
subgroup
Canvas
Type
: { (action: () => void): void } group
Rendering
subgroup
Canvas
Interface
: group
Rendering
subgroup
Shaders
Interface
: group
Rendering
subgroup
Shaders
Type
: 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
Rendering
subgroup
Screen
Function
(g: number): void Set gravity.
param
g- The gravity to set.
since
v2000.0
group
Physics
Function
(): number Get gravity.
since
v3001.0
group
Physics
Function
(d: Vec2): void Set gravity direction.
since
v3001.0
group
Physics
Function
(): Vec2 Get gravity direction.
returns
The gravity direction.
since
v3001.0
group
Physics
Class
: Collision resolution data.
: GameObj The first game object in the collision.
: GameObj The second game object in the collision.
: Vec2 The contact normal.
: number The length of the displacement.
: boolean If the collision is resolved.
get (): Vec2 The displacement source game object have to make to avoid the collision.
()
=> Collision Get a new collision with reversed source and target relationship.
()
=> boolean If the 2 objects have any overlap, or they're just touching edges.
()
=> boolean If the collision happened (roughly) on the left side.
()
=> boolean If the collision happened (roughly) on the right side.
()
=> boolean If the collision happened (roughly) on the top side.
()
=> boolean If the collision happened (roughly) on the bottom side.
()
=> void Prevent collision resolution if not yet resolved.
Function
(src: string | SoundData | Asset<SoundData> | MusicData | Asset<MusicData>, 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
Function
(options?: AudioPlayOpt): AudioPlay Yep. Plays a burp sound.
returns
A control handle.
since
v2000.0
group
Audio
Function
(v: number): void Set the global volume.
param
v- The volume to set.
setVolume(0.5)
since
v3001.1
group
Audio
Function
(): number Get the global volume.
returns
The current volume.
since
v3001.1
group
Audio
Function
(v?: number): number deprecated
Use
// makes everything quieter
volume(0.5)
returns
The new volume or the current volume.
since
v2000.0
group
Audio
Constant
: AudioContext Get the underlying browser AudioContext.
Interface
: Audio play configurations.
?: boolean If audio should start out paused.
?: boolean If audio should be played again from start when its ended.
?: number Volume of audio. 1.0 means full volume, 0.5 means half volume.
?: number Playback speed. 1.0 means normal playback speed, 2.0 means twice as fast.
?: number Detune the sound. Every 100 means a semitone.
// play a random note in the octave
play("noteC", {
detune: randi(0, 12) * 100,
})
?: number The start time, in seconds.
?: 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.
?: AudioNode If the audio node should start out connected to another audio node rather than
KAPLAY's default volume node. Defaults to undefined, i.e. use KAPLAY's volume node.
Interface
: (time?: number): void Start playing audio.
(time: number): void Seek time.
: boolean If the sound is paused.
: number Playback speed of the sound. 1.0 means normal playback speed, 2.0 means twice as fast.
: number Detune the sound. Every 100 means a semitone.
// tune down a semitone
music.detune = -100
// tune up an octave
music.detune = 1200
: number Volume of the sound. 1.0 means full volume, 0.5 means half volume.
?: 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.
: boolean If the audio should start again when it ends.
(): number The current playing time (not accurate if speed is changed).
(): number The total duration.
(action: () => void): KEventController Register an event that runs when audio ends.
(action: () => void): KEventController (node?: AudioNode): void Disconnect the audio node from whatever it is currently connected to
and connect it to the passed-in audio node, or to Kaplay's default volume node
if no node is passed.
Function
(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
Function
(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
Function
(filename: string, dataurl: string): void Trigger a file download from a url.
Function
(filename: string, text: string): void Trigger a text file download.
Function
(filename: string, data: any): void Trigger a json download from a .
Function
(filename: string, blob: Blob): void Trigger a file download from a blob.
Interface
: Screen recording control handle.
(): void Pause the recording.
(): void Resume the recording.
(): Promise<Blob> Stop the recording and get the video data as mp4 Blob.
(filename?: string): void Stop the recording and downloads the file as mp4. Trying to resume later will lead to error.
Function
(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
Function
(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
Function
(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
Function
(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
Function
(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
Function
(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
Function
(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
Function
(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
Function
(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
Function
(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
Function
(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
Function
(opt: DrawUVQuadOpt): void Draw a rectangle with UV data.
param
opt- The draw rect with UV options.
since
v2000.0
group
Draw
Function
(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
Function
(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).
Function
(content: () => void, mask: () => void): void Subtract whatever drawn in content by whatever drawn in mask (mask will not be rendered).
Class
: A picture holding drawing data
group
Draw
subgroup
Picture
()
=> string Serializes this picture to a JSON string
returns
a string containing JSON picture data
Function
(picture?: Picture): void Selects the picture for drawing, erases existing data.
param
picture- The picture to write drawing data to.
since
v4000.0
group
Draw
subgroup
Picture
Function
(picture?: Picture): void Selects the picture for drawing, keeps existing data.
param
picture- The picture to write drawing data to.
since
v4000.0
group
Draw
subgroup
Picture
Function
(): Picture Deselects the current picture for drawing, returning the picture.
returns
The picture which was previously selected.
since
v4000.0
group
Draw
subgroup
Picture
Function
(picture: Picture, opt: DrawPictureOpt): void Draws a picture to the screen. This function can not be used to draw recursively to a picture.
param
picture- The picture to draw
param
opt- Drawing
since
v4000.0
group
Draw
subgroup
Picture
Function
(opt: DrawCanvasOpt): void Draw a canvas.
param
opt- The canvas object.
since
v4000.0
group
Draw
Type
: {} group
Draw
subgroup
Picture
Type
: {} group
Draw
subgroup
Picture
Type
: RenderProps & {} Drawing options for drawPicture
Type
: RenderProps & { : string The text to render.
?: string | FontData | Asset<FontData> | BitmapFontData | Asset<BitmapFontData> The name of font to use.
?: number The size of text (the height of each character).
?: TextAlign Text alignment (default "left")
?: number The maximum width. Will wrap word around if exceed.
?: number The gap between each line (only available for bitmap fonts).
?: number The gap between each character (only available for bitmap fonts).
?: Anchor | Vec2 The anchor point, or the pivot point. Default to "topleft".
?: CharTransform | CharTransformFunc Transform the pos, scale, rotation or color for each character based on the index or char (only available for bitmap fonts).
?: Record<string, CharTransform | CharTransformFunc> Stylesheet for styled chunks, in the syntax of "this is a [stylename]styled[/stylename] word" (only available for bitmap fonts).
?: 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.
Type
: RenderProps & { : string | SpriteData | Asset<SpriteData> The sprite name in the asset manager, or the raw sprite data.
?: number If the sprite is loaded with multiple frames, or sliced, use the frame option to specify which frame to draw.
?: 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.
?: 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.
?: 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.
?: boolean If flip the texture horizontally.
?: boolean If flip the texture vertically.
?: Quad The sub-area to render from the texture, by default it'll render the whole quad(0, 0, 1, 1)
?: Anchor | Vec2 The anchor point, or the pivot point. Default to "topleft".
} How the sprite should look like.
Type
: Omit<RenderProps, "angle" | "scale"> & { : Vec2 Starting point of the line.
: Vec2 Ending point of the line.
?: number The width, or thickness of the line,
} How the line should look like.
Type
: RenderProps & { : Vec2[] The points that make up the polygon
?: boolean If fill the shape with color (set this to false if you only want an outline).
?: number[] Manual triangulation.
?: Vec2 The center point of transformation in relation to the position.
?: number | number[] The radius of each corner.
?: Color[] The color of each vertex.
?: number[] The opacity of each vertex.
?: Vec2[] The uv of each vertex.
?: Texture The texture if uv are supplied.
?: boolean Triangulate concave polygons.
} How the polygon should look like.
Type
: RenderProps & { ?: number The amount of line segments to draw.
?: number The width of the line.
} Type
: DrawCurveOpt & { : Vec2 The the first control point.
: Vec2 The the second control point.
} Type
: RenderProps & { : number Width of the UV quad.
: number Height of the UV quad.
?: boolean If flip the texture horizontally.
?: boolean If flip the texture vertically.
?: Texture The texture to sample for this quad.
?: Quad The texture sampling area.
?: Anchor | Vec2 The anchor point, or the pivot point. Default to "topleft".
} How the UV Quad should look like.
Type
: DrawUVQuadOpt & {} Type
: Omit<RenderProps, "angle"> & { : number Radius of the circle.
?: number Starting angle.
?: boolean If fill the shape with color (set this to false if you only want an outline).
?: [Color, Color] Use gradient instead of solid color.
?: number Multiplier for circle vertices resolution (default 1)
?: Anchor | Vec2 The anchor point, or the pivot point. Default to "topleft".
} How the circle should look like.
Type
: RenderProps & { : number The horizontal radius.
: number The vertical radius.
?: number Starting angle.
?: boolean If fill the shape with color (set this to false if you only want an outline).
?: [Color, Color] Use gradient instead of solid color.
?: number Multiplier for circle vertices resolution (default 1)
?: Anchor | Vec2 The anchor point, or the pivot point. Default to "topleft".
} How the ellipse should look like.
Type
: RenderProps & { : number Width of the rectangle.
: number Height of the rectangle.
?: [Color, Color] Use gradient instead of solid color.
?: boolean If the gradient should be horizontal.
?: boolean If fill the shape with color (set this to false if you only want an outline).
?: number | number[] The radius of each corner.
?: Anchor | Vec2 The anchor point, or the pivot point. Default to "topleft".
} How the rectangle should look like.
Type
: RenderProps & { : Vec2 First point of triangle.
: Vec2 Second point of triangle.
: Vec2 Third point of triangle.
?: boolean If fill the shape with color (set this to false if you only want an outline).
?: number The radius of each corner.
} How the triangle should look like.
Type
: "topleft" | "top" | "topright" | "left" | "center" | "right" | "botleft" | "bot" | "botright" Type
: Rect | Line | Point | Circle | Ellipse | Polygon Type
: RenderProps & {} How the texture should look like.
Constant
: 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
Function
(): string Take a screenshot and get the data url of the image.
returns
The dataURL of the image.
since
v2000.0
group
Debug
Function
(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
Debug
Type
: {} Interface
: An interface for debugging the game.
: boolean Pause the whole game.
: boolean Draw bounding boxes of all objects with area()
component, hover to inspect their states.
: number Global time scale.
: boolean Show the debug log or not.
(): number Current frames per second.
(): number Total number of frames elapsed.
(): number Number of draw calls made last frame.
(): void Step to the next frame. Useful with pausing.
(): void Clear the debug log.
(msg: any): void Log some text to on screen debug log.
(msg: any): void Log an error message to on screen debug log.
: Recording | null The recording handle if currently in recording mode.
(): number Get total number of objects.
Function
(plugin: KAPLAYPlugin<T>): KAPLAYCtx & T Import a plugin.
param
plugin- The plugin to import.
returns
The updated context with the plugin.
since
v2000.0
group
Plugins
Function
(name: string, cb: () => void, when: SystemPhase[]): void Runs a system at the specified events in the pipeline
param
name- The name of the system. Overwrites an existing system if the name has been used before.
param
cb- The function to run.
param
when- When to run the function. See
since
v4000.0
group
Plugins
Enum
:
Type
: {} Type
: (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
Constant
: string All chars in ASCII.
since
v2000.0
group
Constants
Constant
: Vec2 Left directional vector vec2(-1, 0).
since
v2000.0
group
Constants
Constant
: Vec2 Right directional vector vec2(1, 0).
since
v2000.0
group
Constants
Constant
: Vec2 Up directional vector vec2(0, -1).
since
v2000.0
group
Constants
Constant
: Vec2 Down directional vector vec2(0, 1).
since
v2000.0
group
Constants
Constant
: Color Red color.
since
v2000.0
group
Constants
Constant
: Color Green color.
since
v2000.0
group
Constants
Constant
: Color Blue color.
since
v2000.0
group
Constants
Constant
: Color Yellow color.
since
v2000.0
group
Constants
Constant
: Color Cyan color.
since
v2000.0
group
Constants
Constant
: Color Cyan color.
since
v2000.0
group
Constants
Constant
: Color White color.
since
v2000.0
group
Constants
Constant
: Color Black color.
since
v2000.0
group
Constants
Enum
:
Constant
: Engine & {} Internal data that should not be accessed directly.
ignore
readonly
group
Misc
Type
: ReturnType<typeof initGfx> Function
:
{ : (action: () => unknown) => void : (item: WebGLTexture) => void : (item: WebGLBuffer) => void : (item: WebGLBuffer) => void : (item: WebGLFramebuffer) => void : (item: WebGLRenderbuffer) => void : (item: WebGLProgram) => void : (fmt: VertexFormat) => void } Class
: (img: ImageSource)
=> [Texture, Quad, number] (img: ImageSource)
=> [Texture, Quad, number] (packerId: number)
=> void Type
: ReturnType<typeof initAssets> Interface
: Type
: { : number The last game object id used.
: KEventHandler< GameEventMap & GameObjEventMap> Where game object global events are stored.
: GameObj<TimerComp> The root game object, parent of all game objects.
: Vec2 | null The gravity vector of the game.
: Record<SceneName, SceneDef> The scenes of the game.
: Array<SceneState> The scene stack that stores the scene states
: unknown[] The current active scene arguments
: string | null The current scene of the game.
: string[] | null The layers of the game.
: number The default layer index of the game.
: System[] All systems added to the game.
: [System[], System[], System[], System[], System[], System[]] The systems added to the game, sorted by event.
: RNG The default RNG used by rng functions.
: boolean If game just crashed.
: number How many areas are in the game.
: GameObj<FakeMouseComp | PosComp> | null Fake Mouse game obj.
: Set<GameObj> All text inputs in the game.
: Set<string> Deprecated functions we already warned about.
} The "Game" it's all the state related to the game running
Type
: { : number How many draw calls we're doing last frame
: Record<string, FontAtlas> Font atlases
: GfxCtx The graphics context
: Texture Default texture
: FrameBuffer FrameBuffer
: string | null Post Shader, used in postEffect()
: Uniform | ( () => Uniform) | null : Texture The background texture
: Viewport Where the game is rendered.
} Interface
: A frame renderer.
Type
: "none" | "round" | "bevel" | "miter" Type
: "butt" | "round" | "square" Type
: Omit<RenderProps, "angle" | "scale"> & { : Vec2[] The points that should be connected with a line.
?: number The width, or thickness of the lines,
?: number | number[] The radius of each corner.
?: LineJoin Line join style (default "none").
?: LineCap Line cap style (default "none").
?: number Line bias, the position of the line relative to its center (default 0).
?: number Maximum miter length, anything longer becomes bevel.
} How the lines should look like.
Interface
: Current animation data.
: 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.
Interface
: Type
: {} Interface
: (node: number, neighbor: number): number (node: number, goal: number): number (from: number, to: number): number[] (from: Vec2, to: Vec2, opt: any): Vec2[] Interface
: (origin: Vec2, target: Vec2, navigationOpt: any): Vec2[] | undefined Get navigation waypoints to reach the given target from the given origin.
: Graph | undefined The graph to use for navigation.
Interface
: ?: Graph The graph to use for navigation. If null, the ancestors are queried for a pathfinderMap component.
Interface
: (target: Vec2): Vec2[] | undefined Get navigation waypoints to reach the given target from the current position.
: Graph | undefined Get the graph used for navigastion if any.
Interface
: ?: Graph The graph to use for navigation. If null, the ancestors are queried for a pathfinderMap component.
?: any The navigation options depending on the kind of graph used.
Interface
: : Vec2[] | undefined Path to follow. If null, doesn't move.
: number Speed of the movement during patrol.
: Vec2 | undefined Current subgoal, if any.
(cb: (objects: GameObj[]) => void): KEventController Attaches an event handler which is called when using "stop" and the end of the path is reached.
param
cb- The event handler called when the patrol finishes.
Type
: "loop" | "ping-pong" | "stop" Interface
: ?: Vec2[] Path to follow. If null, starts suspended.
?: number Speed of the movement during patrol.
?: PatrolEndBehavior What to do after the last waypoint has been reached.
Type
: () => GameObj<any>[] Type
: SentryCandidatesCb | QueryOpt Type
: "forward" | "reverse" | "ping-pong" Type
: "none" | "linear" | "slerp" | "spline" Interface
: : number Duration of the animation in seconds
?: number Loops, Default is undefined aka infinite
?: TimeDirection Behavior when reaching the end of the animation. Default is forward.
?: EaseFunc Easing function. Default is linear time.
?: Interpolation Interpolation function. Default is linear interpolation.
?: number[] Timestamps in percent for the given keys, if omitted, keys are equally spaced.
?: EaseFunc[] Easings for the given keys, if omitted, easing is used.
Interface
: ?: boolean Changes the angle so it follows the motion, requires the rotate component
?: boolean The animation is added to the base values of pos, angle, scale and opacity instead of replacing them
Interface
: Interface
: The animate component.
(name: string, keys: T[], opts: AnimateOpt): void Animates a property on this object.
param
name- Name of the property to animate.
param
keys- Keys determining the value at a certain point in time.
param
opts- Options.
(name: string): void Removes the animation from the given property.
param
name- Name of the property to remove the animation from.
(): void Removes the animations from all properties
(cb: () => void): KEventController Attaches an event handler which is called when all the animation channels have finished.
param
cb- The event handler called when the animation finishes.
(cb: (name: string) => void): KEventController Attaches an event handler which is called when an animation channels has finished.
param
cb- The event handler called when an animation channel finishes.
: BaseValues Base values for relative animation
: { (time: number): void Move the animation to a specific point in time
: number Returns the duration of the animation
} (): Record<string, AnimationChannel> (): {} Serializes the options of this object to plain Javascript types
Type
: number[] | number[][] Type
: {} Type
: {} & AnimationOptions Type
: {} Interface
: Type
: {} Interface
: Type
: "constant" | "inverseLinear" | "inverseSquared" Type
: {} Interface
: Type
: {} Interface
: Type
: { ?: Vec2[] If the object is about to collide and the collision normal direction is
in here (i.e. the object is moving roughly in this direction), the object won't collide.
Should be a list of unit vectors LEFT
, RIGHT
, UP
, or DOWN
.
Defaults to [UP]
, i.e. the object will only be able to pass through when it
is jumping upwards, but will collide when it is moving downwards or sideways.
?: (this: GameObj<PlatformEffectorComp>, obj: GameObj, normal: Vec2) => boolean A function that determines whether the object should collide.
If present, it overrides the ignoreSides
; if absent, it is
automatically created from ignoreSides
.
} Interface
: : Set<GameObj> A set of the objects that should not collide with this, because shouldCollide
returned true.
Objects in here are automatically removed when they stop colliding, so the casual user shouldn't
need to touch this much. However, if an object is added to this set before the object collides
with the platform effector, it won't collide even if shouldCollide
returns true.
Type
: {} Interface
: (body: GameObj<BodyComp>, submergedArea: Polygon): void (body: GameObj<BodyComp>, submergedArea: Polygon): void Type
: {} Type
: GameObjRaw & { : Record<string, ( () => any)[]> (comp: Comp): void Adds a component or anonymous component.
(id: string): void Removes a component without checking for dependencies
(comp: Comp): void Check if any id of a component's require is not present in _compsIds
, if
there's, throw an error.
param
comp- The component for checking.
(compId: string): void Check if any component (in _compStates
) is dependent of compId, if
there's, throw an error.
param
compId- Component ID for searching.
} Function
:
Vec2 Type
: { : Vec2 The direction the first shape needs to be moved to resolve the collision
: number The distance the first shape needs to be moved to resolve the collision
} Class
: (x: number, y: number)
=> number Class
: Type
: (U extends any ? (k: U) => void : never ) extends (k:
Parsing error with InferType
) => void ? I : never Convert a union type to an intersection type.
Type
: T extends any ? Pick<T, {
[K in
keyof T]:
T[K] extends undefined ? never : K } [keyof T]> : never It removes the properties that are undefined.
Type
: T extends
Parsing error with InferType
? {
[K in
keyof U]:
U[K] } : never It obligates to TypeScript to Expand the type.
Instead of being { id: 1 } | { name: "hi" }
makes
It's { id: 1, name: "hi" }
https://www.totaltypescript.com/concepts/the-prettify-helper
Type
: Expand<UnionToIntersection<Defined<T>>> It merges all the objects into one.
Type
: T extends [
Parsing error with InferType
, ...
Parsing error with InferType
] ? E : never Type
: ReturnType<typeof createEngine> Type
: string Type
: Defined<{
[K in
keyof T]:
K extends keyof Comp ? never : T[K] } > Type
: MergeObj<ReturnType<T[number]>> Type
: Array<T | KAPLAYPlugin<any>> Type
: Record<Tag, string | null> Inspect info for a game object.
Type
: {
[K in
keyof Pick<KAPLAYOpt, "scale">]:
KAPLAYOpt[K] } & KAPLAYOpt Type
: "nearest" | "linear" Texture scaling filter. "nearest" is mainly for sharp pixelated scaling, "linear" means linear interpolation.
Type
: "repeat" | "clampToEdge" Interface
: Common render properties.
?: string | ShaderData | Asset<ShaderData> | null Interface
: ?: number The width, or thickness of the line.
?: Color The color of the line.
?: number Opacity (overrides fill opacity).
?: number Miter limit. If the length of the miter divided by the line width exceeds this limit, the style is converted to a bevel.
Type
: "intersect" | "subtract" Enum
:
Class
: Class
: : ButtonState<KGamepadButton> : Map<KGamepadStick, Vec2> Class
: Type
: ReturnType<typeof initApp> Type
: ReturnType<typeof initAppState> Type
: keyof {
[K in
keyof App]:
[never] } The App method names that will have a helper in GameObjRaw
Class
: A grid is a graph consisting of connected grid cells
(tile: number)
=> number[] (a: number, b: number)
=> number (a: number, b: number)
=> number (start: number, goal: number)
=> number[] (start: Vec2, goal: Vec2)
=> Vec2[] Type
: {} Class
: Class
: One dimensional sweep and prune
: Map<GameObj<AreaComp>, [SapEdge, SapEdge]> (obj: GameObj<AreaComp>)
=> void Add the object and its edges to the list
param
obj- The object to add
(obj: GameObj<AreaComp>)
=> void Remove the object and its edges from the list
param
obj- The object to remove
()
=> void Update edges and sort
Class
: : (a: T, b: T) => boolean (item: T)
=> void Insert an item into the binary heap
()
=> 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
()
=> void Remove all items
(index1: number, index2: number)
=> void get (): number Returns the amount of items
Function
:
{} Function
:
(ggl: GfxCtx, spriteAtlasPadding: number) => { : AssetBucket<SpriteData> : AssetBucket<SerializedGameObj> } Function
:
(gopt: KAPLAYOpt) => { : {} & KAPLAYOpt<any, any> : { : { : Map<MouseButton, string[]> : Map<KGamepadButton, string[]> : ButtonState<MouseButton> : { : ButtonState<KGamepadButton> : Map<KGamepadStick, Vec2> } : Map<number, { : ButtonState<KGamepadButton> : Map<KGamepadStick, Vec2> }> : "mouse" | "keyboard" | "gamepad" | null : KEventHandler<AppEventMap> } : (fixedUpdate: () => void, update: (processInput: () => void, resetInput: () => void) => void) => void : (k?: Key | Key[]) => boolean : (k?: Key | Key[]) => boolean : (k?: Key | Key[]) => boolean : (k?: Key | Key[]) => boolean : (m?: MouseButton) => boolean : (m?: MouseButton) => boolean : (m?: MouseButton) => boolean : (btn?: KGamepadButton | KGamepadButton[]) => boolean : (btn?: KGamepadButton | KGamepadButton[]) => boolean : (btn?: KGamepadButton | KGamepadButton[]) => boolean : (stick: KGamepadStick) => Vec2 : (btn?: string | string[]) => boolean : (btn?: string | string[]) => boolean : (btn?: string | string[]) => boolean : (btn: string, binding: ButtonBinding) => void : (btn: string) => ButtonBinding : (action: () => void) => KEventController : ( (action: (key: Key) => void) => KEventController) & ( (key: Key | Key[], action: (key: Key) => void) => KEventController) : ( (action: (key: Key) => void) => KEventController) & ( (key: Key | Key[], action: (key: Key) => void) => KEventController) : ( (action: (key: Key) => void) => KEventController) & ( (key: Key | Key[], action: (key: Key) => void) => KEventController) : ( (action: (key: Key) => void) => KEventController) & ( (key: Key | Key[], action: (key: Key) => void) => KEventController) : ( (action: (m: MouseButton) => void) => KEventController) & ( (mouse: MouseButton | MouseButton[], action: (m: MouseButton) => void) => KEventController) : ( (action: (m: MouseButton) => void) => KEventController) & ( (mouse: MouseButton | MouseButton[], action: (m: MouseButton) => void) => KEventController) : ( (action: (m: MouseButton) => void) => KEventController) & ( (mouse: MouseButton | MouseButton[], action: (m: MouseButton) => void) => KEventController) : (f: (pos: Vec2, dpos: Vec2) => void) => KEventController : (action: (ch: string) => void) => KEventController : (f: (pos: Vec2, t: Touch) => void) => KEventController : (f: (pos: Vec2, t: Touch) => void) => KEventController : (f: (pos: Vec2, t: Touch) => void) => KEventController : (action: (delta: Vec2) => void) => KEventController : (action: () => void) => KEventController : (action: () => void) => KEventController : ( (action: (btn: KGamepadButton, gamepad: KGamepad) => void) => KEventController) & ( (btn: KGamepadButton, action: (btn: KGamepadButton, gamepad: KGamepad) => void) => KEventController) : ( (action: (btn: KGamepadButton, gamepad: KGamepad) => void) => KEventController) & ( (btn: KGamepadButton | KGamepadButton[], action: (btn: KGamepadButton, gamepad: KGamepad) => void) => KEventController) : ( (action: (btn: KGamepadButton, gamepad: KGamepad) => void) => KEventController) & ( (btn: KGamepadButton | KGamepadButton[], action: (btn: KGamepadButton, gamepad: KGamepad) => void) => KEventController) : (stick: KGamepadStick, action: (value: Vec2, gp: KGamepad) => void) => KEventController : (action: (gamepad: KGamepad) => void) => KEventController : (action: (gamepad: KGamepad) => void) => KEventController : ( (action: (btn: string) => void) => KEventController) & ( (btn: string | string, action: (btn: string) => void) => KEventController) : ( (action: (btn: string) => void) => KEventController) & ( (btn: string | string, action: (btn: string) => void) => KEventController) : ( (action: (btn: string) => void) => KEventController) & ( (btn: string | string, action: (btn: string) => void) => KEventController) : () => "keyboard" | "gamepad" | "mouse" | null : KEventHandler<AppEventMap> } : { : (action: () => unknown) => void : (item: WebGLTexture) => void : (item: WebGLBuffer) => void : (item: WebGLBuffer) => void : (item: WebGLFramebuffer) => void : (item: WebGLRenderbuffer) => void : (item: WebGLProgram) => void : (fmt: VertexFormat) => void } : { : AssetBucket<SpriteData> : AssetBucket<SerializedGameObj> } : CanvasRenderingContext2D | null } Function
:
(opt: { ?: Record<string, GamepadDef> }) => { : Map<MouseButton, string[]> : Map<KGamepadButton, string[]> : ButtonState<MouseButton> : Map<number, GamepadState> : "mouse" | "keyboard" | "gamepad" | null : KEventHandler<AppEventMap> } Function
:
(opt: {} & KAPLAYOpt) => { : { : Map<MouseButton, string[]> : Map<KGamepadButton, string[]> : ButtonState<MouseButton> : Map<number, GamepadState> : "mouse" | "keyboard" | "gamepad" | null : KEventHandler<AppEventMap> } : (fixedUpdate: () => void, update: (processInput: () => void, resetInput: () => void) => void) => void : (k?: Key | Key[]) => boolean : (k?: Key | Key[]) => boolean : (k?: Key | Key[]) => boolean : (k?: Key | Key[]) => boolean : (m?: MouseButton) => boolean : (m?: MouseButton) => boolean : (m?: MouseButton) => boolean : (btn?: KGamepadButton | KGamepadButton[]) => boolean : (btn?: KGamepadButton | KGamepadButton[]) => boolean : (btn?: KGamepadButton | KGamepadButton[]) => boolean : (stick: KGamepadStick) => Vec2 : (btn?: string | string[]) => boolean : (btn?: string | string[]) => boolean : (btn?: string | string[]) => boolean : (btn: string, binding: ButtonBinding) => void : (btn: string) => ButtonBinding : (action: () => void) => KEventController : ( (action: (key: Key) => void) => KEventController) & ( (key: Key | Key[], action: (key: Key) => void) => KEventController) : ( (action: (key: Key) => void) => KEventController) & ( (key: Key | Key[], action: (key: Key) => void) => KEventController) : ( (action: (key: Key) => void) => KEventController) & ( (key: Key | Key[], action: (key: Key) => void) => KEventController) : ( (action: (key: Key) => void) => KEventController) & ( (key: Key | Key[], action: (key: Key) => void) => KEventController) : ( (action: (m: MouseButton) => void) => KEventController) & ( (mouse: MouseButton | MouseButton[], action: (m: MouseButton) => void) => KEventController) : ( (action: (m: MouseButton) => void) => KEventController) & ( (mouse: MouseButton | MouseButton[], action: (m: MouseButton) => void) => KEventController) : ( (action: (m: MouseButton) => void) => KEventController) & ( (mouse: MouseButton | MouseButton[], action: (m: MouseButton) => void) => KEventController) : (f: (pos: Vec2, dpos: Vec2) => void) => KEventController : (action: (ch: string) => void) => KEventController : (f: (pos: Vec2, t: Touch) => void) => KEventController : (f: (pos: Vec2, t: Touch) => void) => KEventController : (f: (pos: Vec2, t: Touch) => void) => KEventController : (action: (delta: Vec2) => void) => KEventController : (action: () => void) => KEventController : (action: () => void) => KEventController : ( (action: (btn: KGamepadButton, gamepad: KGamepad) => void) => KEventController) & ( (btn: KGamepadButton, action: (btn: KGamepadButton, gamepad: KGamepad) => void) => KEventController) : ( (action: (btn: KGamepadButton, gamepad: KGamepad) => void) => KEventController) & ( (btn: KGamepadButton | KGamepadButton[], action: (btn: KGamepadButton, gamepad: KGamepad) => void) => KEventController) : ( (action: (btn: KGamepadButton, gamepad: KGamepad) => void) => KEventController) & ( (btn: KGamepadButton | KGamepadButton[], action: (btn: KGamepadButton, gamepad: KGamepad) => void) => KEventController) : (stick: KGamepadStick, action: (value: Vec2, gp: KGamepad) => void) => KEventController : (action: (gamepad: KGamepad) => void) => KEventController : (action: (gamepad: KGamepad) => void) => KEventController : ( (action: (btn: string) => void) => KEventController) & ( (btn: string | string, action: (btn: string) => void) => KEventController) : ( (action: (btn: string) => void) => KEventController) & ( (btn: string | string, action: (btn: string) => void) => KEventController) : ( (action: (btn: string) => void) => KEventController) & ( (btn: string | string, action: (btn: string) => void) => KEventController) : () => "keyboard" | "gamepad" | "mouse" | null : KEventHandler<AppEventMap> }