API Quick Reference
Big Picture
App
Images, ...
Scene
Scene
...
Sprite
Entity
World
App
:
Resource management and event loop.
Scene
:
Game state management and event handling.
World
:
Container where Entities are placed in.
Entity
:
In-game character.
Sprite
:
Graphical object to be shown.
Basic Classes
Every game has exactly one App
object.
It does the basic pluming and resource management (images and sounds); it has
an event loop and connect the game with all the external parts (i.e. a browser).
Typically, you don't have to change this class.
new App( width , height , elemId ="game", framerate =30)
Creates a new app with given HTML5 resources.
.size
Canvas size.
.framerate
Frame rate.
.elem
HTML element where a canvas is embedded.
.canvas
The <canvas>
element.
.ctx
The CanvasRenderingContext2D
object.
.audioContext
The AudioContext
object.
.images
Set of available HTMLImageElement
objects.
.sounds
Set of available HTMLAudioElement
objects.
.labels
Set of available HTMLDivElement
objects.
.scene
Current Scene
object that is running.
.active
true
if the game is not suspended.
.keys[]
States of the current keys.
.keyDir
State of the current 2D input (arrow keys).
.mousePos
Current position of the mouse pointer.
.mouseButton
Current state of the mouse button.
.init(scene )
Initializes the game with the first Scene
.
.start()
Starts the game.
.stop()
Stops the game.
.addElement(bounds )
Adds a new <div>
element to the canvas.
.removeElement(elem )
Removes the element from the canvas.
.lockKeys(t =1)
Blocks the keyboard input to prevent accidental input
(in a scene transition).
.setMusic( name =null, start =0, end =0)
Starts playing the music. When name is null
, it stops music.
.playSound(name , start =0)
Plays the specified sound.
.setScene(scene )
Switches the game to the scene
.
.post(msg)
Queues a function that is to be executed at the end of the frame.
A Scene
is a mini-app or "mode" within the App.
At each moment, exactly one Scene
is responsible
for all the user interaction. This is primarily what consists of
a game logic. Euskit supports multiple Scene
s,
but it's possible to create an entire game with just one Scene
.
See Basic Player Control
and Change Scene .
new Scene()
Creates a new scene.
new HTMLScene(text )
Creates a new scene with a static HTML text.
new GameScene()
Creates a new scene with a World
object.
.screen
Canvas area Rect
object.
.reset()
Resets the scene to its initial state.
.changeScene(scene )
Signals to switch a scene.
.render(ctx )
Displays the scene.
.onStart()
Invoked when the scene is started.
.onStop()
Invoked when the scene is finished.
.onTick()
Invoked for every frame.
.onDirChanged(v )
Invoked when a directional input is changed.
.onButtonPressed(keySym )
Invoked when the button state is pressed.
.onButtonReleased(keySym )
Invoked when the button state is released.
.onKeyDown(keyCode )
Invoked when a key is pressed.
.onKeyUp(keyCode )
Invoked when a key is released.
.onKeyPress(charCode )
Invoked when a character is typed.
.onMouseDown(p , button )
Invoked when a mouse button is pressed.
.onMouseUp(p , button )
Invoked when a mouse button is released.
.onMouseMove(p )
Invoked when a mouse pointer is moved.
.onFocus()
Invoked when the window is focused.
.onBlue()
Invoked when the focus is lost.
A World
is a container of Entity
s.
The entities which belong here are rendered and their collision is detected.
See Basic Player Control
and Spawn Another Entity .
new World()
Creates a new world.
.mouseDown
Fired when a mouse is pressed on an Entity
.
.mouseUp
Fired when a mouse is released on an Entity
.
.area
Entire area where entities can move around.
.window
Visible part of the world that is rendered.
.entities
List of the Entity
s that belong to this world.
.mouseFocus
The Entity
that has the mouse focus (null
if none).
.mouseActive
The Entity
that is currently activated (null
if none).
.add(entity )
Adds an Entity
to this world.
.remove(entity )
Removes an Entity
from this world.
.render(ctx )
Renders every Entity
s in the world.
.findEntityAt(p )
Returns an Entity that overlaps with point p
.
.setCenter( target , bounds =null)
Moves the window to cover target
, but not exceeding bounds
.
.moveCenter(v )
Moves the center of the window by v
.
.moveAll(v)
Moves all the sprites by v
.
.getEntityColliders( (e:Entity)=>boolean , range =null)
Returns a list of Entity
colliders that overlaps with range
(if given).
.applyEntities( (e:Entity)=>boolean , collider =null)
Applies the function to each Entity e
that overlaps with collider
(if given).
.onMouseDown(p , button )
Invoked when a mouse button is pressed.
.onMouseUp(p , button )
Invoked when a mouse button is released.
.onMouseMove(p )
Invoked when a mouse pointer is moved.
A Task
is a base class of Entity
.
new Task()
Creates a new empty task.
new SoundTask( sound , soundStart =MP3_GAP, soundEnd =0)
Task that plays a sound.
.stopped
Signal fired when the task stops.
.parent
TaskList
that the task belongs to.
.lifetime
Duration that the task can run.
.startTime
Time the task started.
.getTime()
Elapsed time since the task has started (in seconds).
.isScheduled()
True if the task is going to start.
.isRunning()
True if the task is in running state.
.stop()
Terminates the task.
.chain(task , signal =null)
Schedules another task to be started when this task stops.
.onStart()
Invoked when the task is started.
.onStop()
Invoked when the task is stopped.
.onTick()
Invoked at every frame while the task is running.
An Entity
is a main object for game characters.
Each Entity is a Task
and has a Collider
and one or more
Sprites.
See Restrict Entity within Bounds
and Spawn Another Entity .
new Entity(pos )
Creates a new entity at a given position.
.pos
Entity position.
.collider
Rect
/Circle
for the entity's collider.
.sprites
Sprite
s that belongs to this entity.
.order
Order of the entity being rendered.
.rotation
Rotation of the sprite (in radian).
.scale
Vector for the scale of the sprite.
.alpha
Alpha value of the sprite.
.isVisible()
Returns true
if the entity sprite is visible.
.render(ctx )
Render the entity.
.getCollider()
Returns the collider for the current position.
.onCollided(entity )
Invoked when the entity collides another entity.
.getMove(v )
Trims the vector v
so that it satisfies the contraints.
A Sprite
is something to be displayed.
new RectSprite(color , dstRect )
Sprite with a filled rectangle.
new OvalSprite(color , dstRect )
Sprite with a filled oval.
new CanvasSprite( canvas , srcRect =null, dstRect =null)
Sprite that refers to a portion of
<canvas>
element.
new HTMLSprite( image , srcRect =null, dstRect =null)
Sprite that refers to a portion of
<img>
element.
new TiledSprite( sprite , bounds , offset =null)
Sprite that is composed of another Sprite.
new StarSprite( bounds , nstars , maxdepth =3, sprites =null)
Sprite that can be used for "star flowing" effects.
.getBounds()
Returns the bounds rectangle of the Sprite.
.render(ctx )
Renders the image at (0, 0) in the given Context.
Specialized Objects
A Particle
is an Entity
that
keeps moving towards a specific direction.
new Particle(pos )
Creates a new particle that keeps moving.
.movement
Velocity of the object.
.getFrame()
Returns the Rect
where the entity is kept alive within.
An Entity
that is affected by gravity.
new PlatformerEntity( physics , tilemap , fence , pos )
Creates a new entity that is affected by gravity.
.setJump(jumpend )
Starts a jump maneuver that ends at t=jumpend
.
.fall()
Invoked for every update.
.isJumping()
true
if the entity is jumping.
.isLanded()
true
if the entity is landed on a platform.
.canJump()
true
if the entity can jump.
.canFall()
true
if the entity can fall.
.onJumped()
Invoked when the entity starts jumping.
.onLanded()
Invoked when the entity is landed.
A Scene
that has a World
and convenient methods.
new GameScene()
Creates a new scene.
.add(entity )
Adds an Entity
to the world.
.remove(entity )
Removes an Entity
from the world.
Text Library
Font (text.ts
)
A Font
represents a monospace bitmap font.
new Font( glyphs , color =null, scale =1)
Font with a given glyphs
.
new InvertedFont( glyphs , color =null, scale =1)
Inverted Font.
new ShadowFont( glyphs , color =null, scale =1, shadowColor ='black', shadowDist =1)
Font with shadow.
.width
Width of each character.
.height
Height of each character.
.background
Background color (null
for transparent).
.getSize(text )
Computes the pixel size for a given text.
.renderString( ctx , text , x , y )
Draws the text at a given location.
TextBox : Sprite (text.ts
)
A type of Sprite
for a monospaced text.
See Display Text .
new TextBox( frame , font =null)
TextBox with a given frame and font.
.frame
Area of text displayed.
.font
Default font.
.header
Header string for each line.
.lineSpace
Space between lines.
.padding
Padding between text and frame.
.background
Background color (null
for transparency).
.borderColor
Border color (null
for no border).
.borderWidth
Border width.
.getBounds()
Returns the frame rectangle.
.getInnerBounds()
Returns the area that the actual text is displayed.
.clear()
Clears all the texts displayed.
.addSegment(pt , text , font =null)
Add a text segment at a given location.
.addText( text , font =null)
Append a text.
.addNewline(font =null)
Append a newline.
.putText(lines , halign ='left', valign ='top')
Layout the given lines.
.getSize(lines , font =null)
Computes the pixel size for a given text.
.wrapLines(text , font =null, header =null)
Split the text into lines that can fit the textbox.
.render(ctx)
Draws the text.
DialogBox : Entity (text.ts
)
This is a rather complex class for showing text dialog or menu.
See Typewriter Effect and
Menu Selection .
new DialogBox( textbox , hiFont =null)
Create a new DialogBox with a given highlight font.
.addPause(duration )
Schedule a pause during a dialog.
.addDisplay( text , speed =-1, sound =null, font =null)
Schedule displaying text with a given speed, font and sound effect.
.addMenu()
Schedule displaying a menu.
.addWait()
Schedule waiting.
.ff()
Fast-forward and show all the texts.
.clear()
Clears all the texts and tasks.
BannerBox : Entity (text.ts
)
An Entity
for showing text banners.
See Blinking Banner .
new BannerBox( frame , font , lines =null, lineSpace =4)
TextBox with a given frame and font.
.interval
Blinking interval (0: no blinking).
.putText(lines , halign ='center', valign ='center')
Layout the given lines.
TextParticle : BannerBox (text.ts
)
A short-lived text particle.
new TextParticle( pos , font , text , borderWidth =1)
Creates a new text particle.
.movement
Velocity of the object.
Animation Library
TODO
Pathfinding Library
TODO
Utility Classes
A Signal
represents an event that is attached to a
certain object and other objects can get notified.
See Signal Subscription/Firing .
new Signal(baseargs , ...)
New Signal
object with given baseargs
.
.receivers
List of the receiver functions.
.subscribe(receiver )
Adds receiver
to the subscriber list.
.unsubscribe(receiver )
Removes receiver
from the subscriber list.
.fire(extraargs , ...)
Sends a message to all the subscribers.
Each receiver function gets (baseargs
+ extraargs
)
for arguments.
A Color
represents an RGBA value.
new Color(r , g , b , a =1.0)
New Color
object for RGBA values.
.r
Red value.
.g
Green value.
.b
Blue value.
.a
Alpha value.
.setAlpha(a )
Creates a Color
with a given alpha.
.multiply(t )
Multiplies each component by t
.
.blend(color , t )
Blends with another Color
with ratio t
.
Color.generate(h , v =1.0)
Creates a Color
with a given hue.
A Vec2
represents two-dimensional vector that has (x, y) elements.
new Vec2(x =0, y =0)
New 2D vector (x
, y
).
.x
X value.
.y
Y value.
.copy()
Duplicates the vector.
.equals(p )
true
if the vector is identical to p
.
.isZero()
true
if the vector is zero length.
.len2()
Length2 of the vector.
.len()
Length of the vector.
.sign()
(sign(x)
, sign(y)
).
.add(v )
(this
+ v
).
.sub(v )
(this
- v
).
.scale(n )
(n
⋅ this
).
.distance(p )
|this
- p
|.
.clamp(bounds )
(clamp(x)
, clamp(y)
).
.move(dx , dy )
(x+dx
, y+dy
).
.lerp(p , t )
(this*(1-t) + p*t)
.
.rotate(d )
Creates a rotated vector in radian (clockwise...0<d
)
.rot90(d )
Creates a rotated vector by 90 degrees (clockwise...0<d
)
.expand( dw , dh , anchor ='c')
Creates a Rect
with the point as an anchor.
A Vec3
represents three-dimensional vector that has (x, y, z) elements.
new Vec3(x =0, y =0, z =0)
New 3D vector (x
, y
, z
).
.x
X value.
.y
Y value.
.z
Z value.
.copy()
Duplicates the vector.
.equals(p )
true
if p
is identical.
.isZero()
true
if the vector is zero length.
.len2()
Length2 of the vector.
.len()
Length of the vector.
.sign()
(sign(x)
, sign(y)
, sign(z)
).
.add(v )
(this
+ v
).
.sub(v )
(this
- v
).
.scale(n )
(n
⋅ this
).
.distance(p )
|this
- p
|.
.clamp(bounds )
(clamp(x)
, clamp(y)
, clamp(z)
).
.move(dx , dy , dz )
(x+dx
, y+dy
, z+dz
).
.lerp(p , t )
(this*(1-t) + p*t)
.
A Collider
is an abstract geometric object
that can be used for hit detection.
.copy()
Duplicates the collider.
.move(dx , dy )
Creates a collider moved by (dx
, dy
).
.add(v )
Creates a collider moved by v
.
.sub(v )
Creates a collider moved by -v
.
.equals(collider )
true
if collider
is identical.
.overlaps(collider )
true
if this collider overlaps collider
.
.contact(v , collider )
Trims a vector so that collider
doesn't collide with this.
.getAABB()
Returns the AABB of the collider.
A Shape
is an abstract object that has a clear boundary and
represents an enclosed shape.
.isZero()
true
if the shape is empty.
.containsPt(p )
true
if the shape contains p
.
.edgePt(t )
Returns a point on the contour.
.rndPt()
Returns a random point within the shape.
.rndPtEdge()
Returns a random point on the edge.
A Rect
object is a 2D rectangle that
has its position (x, y) and size (width, height).
new Rect( x =0, y =0, width =0, height =0)
New rectangle (x
, y
, width
, height
).
.x
X value of the top-left corner.
.y
Y value of the top-left corner.
.width
Width of the rectangle.
.height
Height of the rectangle.
.x1()
X value of the right edge of the rectangle.
.y1()
Y value of the bottom edge of the rectangle.
.cx()
Center x of the rectangle.
.cy()
Center y of the rectangle.
.center()
Center point of the rectangle.
.topLeft()
Top left corner of the rectangle.
.topRight()
Top right corner of the rectangle.
.bottomLeft()
Bottom left corner of the rectangle.
.bottomRight()
Bottom right corner of the rectangle.
.anchor(anchor )
Anchor point of the rectangle:
nw
n
ne
w
e
sw
s
se
.edge(direction )
Returns an edge of the rectangle.
n
w
e
s
.inflate(dw , dh )
Creates a inflated/deflated rectangle by (dw×2
, dh×2
):
dw
dh
dh
dw
.expand( dw , dh , anchor ='c')
Creates an expanded rectangle by (dw
, dh
).
.resize( w , h , anchor ='c')
Creates a resized rectangle.
.xdistance(rect )
X-distance to rect
.
.ydistance(rect )
Y-distance to rect
.
.containsRect(rect )
true
if the rectangle contains rect
.
.overlapsRect(rect )
true
if the rectangle overlaps rect
.
.overlapsCircle(circle )
true
if the rectangle overlaps circle
.
.union(rect )
Combines two rectangles (union).
.intersection(rect )
Combines two rectangles (intersection).
.clamp(bounds )
Moves the rectangle so that it fits bounds
.
.modPt(p )
Creates a modulo point with the rectangle.
.contactRect(v , rect )
Trims a vector so that rect
doesn't collide with this.
.boundRect(v , rect )
Trims a vector so that rect
is restricted inside this.
A Circle
represents a circle that has its center and radius.
new Circle(center , radius =0)
New circle with the given center and radius.
.center
Center of the circle.
.radius
Radius of the circle.
.inflate(dr )
Creates a inflated/deflated circle by dr
.
.resize(radius )
Creates a resized circle.
.distance(p )
Distance to point p
.
.containsCircle(circle )
true
if the circle contains another circle
.
.overlapsCircle(circle )
true
if the circle overlaps another circle
.
.overlapsRect(rect )
true
if the circle overlaps rect
.
.clamp(bounds )
Moves the circle so that it fits bounds
.
.contactCircle(v , circle )
Trims a vector so that circle
doesn't collide with this.
A Box
is a 3D cuboid that has its position and size
both as Vec3
.
new Box(origin , size =null)
New Box with (origin
, size
).
.origin
Origin of the box.
.size
Size of the box.
.copy()
Duplicates the box.
.equals(box )
true
if box
is identical.
.isZero()
true
if the box is empty.
.center()
Center of the box.
.surface(vx , vy , vz )
Returns the plane of the given surface.
.anchor(vx =0, vy =0, vz =0)
Anchor point of the box.
.move(dx , dy , dz )
Creates a box moved by (dx
, dy
, dz
).
.add(v )
Creates a box moved by v
.
.sub(v )
Creates a box moved by -v
.
.inflate(dx , dy , dz )
Creates a inflated/deflated box by (dx
, dy
, dz
).
.xdistance(box )
X-distance to box
.
.ydistance(box )
Y-distance to box
.
.zdistance(box )
Z-distance to box
.
.union(box )
Combines two boxes (union).
.intersection(box )
Combines two boxes (intersection).
.clamp(bounds )
Moves the box so that it fits bounds
.
.rndPt()
Creates a random point within the box.
.containsPt(p )
true
if the box contains p
.
.overlapsBox(box )
true
if the box overlaps box
.
.contactBox(v , box )
Trims a vector so that box
doesn't collide with this.
.union(box )
Combines two boxes (union).
.intersection(box )
Combines two boxses (intersection).
.clamp(bounds )
Moves the box so that it fits bounds
.
A TileMap
represents a two-dimensional array that holds map tiles.
See Create TileMap
new TileMap( tilesize , width , height , map =null)
New TileMap for a given size.
.tilesize
Tile size.
.width
Number of tiles that fit horizontally in the map.
.height
Number of tiles that fit vertically in the map.
.bounds
Bounds of the map in the actual size.
.map
Int32Array[] for the map data. Optionally given at construction.
.get(x , y )
Gets a tile at a specific position.
.set(x , y , c )
Sets a tile at a specific position. (Clears the RangeMap cache.)
.fill(c , rect =null)
Fills tiles in a given area.
.copy()
Copies the tilemap.
.coord2map(rect )
Converts an actual Rect/Vec2 to the tile cells.
.map2coord(rect )
Converts a Rect/Vec2 for tile cells to the actual size.
.apply( (x,y,c) => boolean , rect =null)
Applies a function to tiles.
.shift(vx , vy , rect =null)
Shift all the cells in the given area.
.findTile( (c) => boolean , rect =null)
Returns the position of the first tile in the given area.
.findTileByCoord( (c) => boolean , range )
Returns the position of the first tile in the given area.
.getTileRects( (c) => boolean , range )
Returns a list of actual rectangles for tiles.
.getRangeMap( key , (c) => boolean )
Creates a RangeMap
object for this tilemap.
.renderFromBottomLeft( ctx , ft , x0 =0, y0 =0, w =0, h =0)
Renders the tiles from bottom left for a given tile set.
.renderFromTopRight( ctx , ft , x0 =0, y0 =0, w =0, h =0)
Renders the tiles from top right for a given tile set.
.renderWindowFromBottomLeft( ctx , window , ft )
Renders the tiles from bottom left within a window.
.renderWindowFromTopRight( ctx , window , ft )
Renders the tiles from top right within a window.
A RangeMap
is a partial copy of TileMap
that allows range queries for specific tiles.
Note:
This object is always returned by TileMap.getRangeMap()
method
and not explicitly created by a user.
.width
Number of tiles that fit horizontally in the map.
.height
Number of tiles that fit vertically in the map.
.get(x0 , y0 , x1 , y1 )
Returns the number of specific tiles within the given area.
.exists(rect )
true
if a specific tile exists within the given area.
A set of Sprite
objects indexed by a number.
new ImageSpriteSheet(image, size, [origin] )
Creates a SpriteSheet
from <img>
.
new ArraySpriteSheet(sprites)
Creates a SpriteSheet
from an array of Sprite
s.
.get(i, [j, [w, [h, [origin]]]] )
Returns the i,j
-th Sprite
.
new PhysicsConfig()
Creates a new configuration.
.maxspeed
Vector for the maximum speed (absolute values).
.jumpfunc
Gravity function (vy, t) => number
.isObstacle
Function (c) => boolean
that returns true if the tile is an obstacle.
.isGrabbable
Function (c) => boolean
that returns true if the tile is grabbable (e.g. ladders).
.isStoppable
Function (c) => boolean
that returns true if the tile is stoppable.
Manages a list of Task
s.
new ParallelTaskList()
Tasklist that runs given tasks parallelly.
new SequentialTaskList()
Tasklist that runs given tasks sequentially.
.onStart()
Initializes the task list.
.onTick()
Invoked at every frame. Update the current tasks.
.add(task)
Adds a task to the list.
.remove(task)
Removes a task from the list.
.stopWhenEmpty
Set true
to automatically kill the queue when there's no Task
.
Functions
Main function (main.ts
)
APP
Global App
instance.
addInitHook(() => {} )
Has a hook executed after the page is loaded.
main( ctor , width =320, height =240, canvasId ='game', framerate =30)
Specifies the canvas size and the initial constructor of a Scene
object.
(without arg)
How to Use
<script>
class Scene1 extends Scene { ... }
</script>
<body onload="main(Scene1, 'game', 320, 240, 30);">
<div id="main" style="width:640px; height:480px"></div>
Misc. functions (utils.ts
)
log(msg , ...)
Displays the messages to the console.
assert(cond , msg ="assertion error")
Throws an exception when the condition is not met.
applyMixins(ctor , bases )
Configures a new class.
removeChildren(node , name )
Removes all child HTML nodes.
Numeric functions (utils.ts
)
fmod(x , y )
Better mod
function; i.e. fmod(-3,2)=1
.
int(x )
Equivalent to Math.floor
.
upperbound(x , y )
Limits a value to min(x
, y
).
lowerbound(x , y )
Limits a value to max(x
, y
).
clamp(v0 , v , v1 )
Limits a value within [v0
, v1
].
sign(v )
Returns -1, 0 or +1 based on the sign of v
.
phase(t , interval , n =2)
Returns the phase for time t
.
lerp(t , a , b )
Returns the interpolation of t
for [a
, b
].
frnd(a , b =0)
Generates a value [0,a
) or [a
,b
)
rnd(a , b =0)
Generates an integer value [0,a
) or [a
,b
)
getTime()
Returns the current time in seconds.
format(v , n =3, c =' ')
Formats a number as a string.
noise2d(x , y )
Simplified Perlin Noise function.
Array functions (utils.ts
)
choice(a )
Returns a random element of a
.
removeElement(a , obj )
Removes an element from a
.
range(n )
Returns an array filled with a sequence [0, n
-1].
str2array(img )
Converts a string to a number array.
makeMatrix(rows , cols , value =0)
Creates a 2D matrix for a given size.
Graphics functions (utils.ts
)
createCanvas(width , height )
Creates a <canvas>
element.
getEdgeyContext(canvas )
Creates a CanvasRenderingContext2D
.
image2array(img )
Converts an image to an 2D array.
fillRect(ctx , rect )
Fills a rectangle.
strokeRect(ctx , rect )
Draws a rectangle.
ellipse(ctx , cx , cy , rx , ry )
Draws an ellipse at (cx, cy).
drawImageScaled( ctx , img , sx , sy , sw , sh , dx , dy , dw , dh )
Draws a flipped image.
getKeySym(keycode )
Returns the KeySym
for keyCode
.