game.js docs

Overview

game.js is a file to help with making games in the html canvas. This is mainly meant for pixel art games, as the way stuff is rendered is very pixelated.

Jump to

setup structure graphics physics audio input utils

setup

Canvas

For game.js to work, there needs to be a canvas element in your html file, that has id "game"

Loading Assets

assign images and audio an array with the sources relative to the html file in which games.js is used.

The first string of an array will be added on to the start of following strings. Example:

    images = [
        "folder1/",
        "pic1.png",
        [
            "subfolder/"
            "pic2.png"
        ],
        "pic3.png"
    ];
                        

will result in

    "folder1/pic1.png",
    "folder1/subfolder/pic2.png",
    "folder1/pic3.png"
                        

Start the game

After stuff in your scripts has loaded, call setup(framerate). Now the user can click play to start the game

Note: the framerate is only used for physics updates, drawing frames uses requestAnimationFrame()

After assets load

If you need to run code once, after all assets have been loaded,

create a function called onAssetsLoaded(). If this exists in your code it will be called after assets are loaded

structure

There are two functions that must be defined in your script, and two optional functions.

Physics

update() - required, will try to be called at the framerate set with setup(framerate)

input() - optional, if included, will try to be called every 4 milliseconds. Anything can be run here, but it is recommended to just run input code.

Graphics

draw() - required, uses requestAnimationFrame(), so frame rate will vary but is mostly 60fps.

functions found in graphics can be called here.

absoluteDraw() - optional, if included, called immediately after draw(), same as draw(), except graphics ignore the camera when called here. Good for things like UI.

graphics

Variables

sprites - images that have been loaded in. The name of a sprite is just the file name without the file extension.

Example: an image loaded like this: images = [ "assets/", "pic.png" ] can be accessed like: sprites.pic

canvasScale - screen pixels per game pixels. Uses css to scale the canvas. This was implemented very poorly,

so if you want use it, try something like this: function update() { if(screenSize == "1:1") {canvasScale = 2} }

cursor - set a sprite as the cursor

.sprite - sprite to show

.alignment - 0 = top left, 1 = centered

cw - canvas width

ch - canvas height

Functions

img(sprite, x, y, angle=0, sx=1, sy=1) - draws a sprite centered on x,y. Angle is rotation in radians. sx, sy is scale x and y to draw the image at

imgIgnoreCutoff(img, x, y, angle=0, sx=1, sy=1) - same as img, but will draw the image even if off the canvas. If an image is larger than the canvas, it will break img(), so use this.

Note: color can be any HTML color as a string

rect(x, y, w, h, color) - draws a rectangle centered on the x,y. w is width, h is height

circle(x, y, r, color) - draws a circle centered on the x,y. r is radius

shape(x, y, relitivePoints, color) - connects the points given in relitivePoints, relative to x,y then fills in the shape. relitivePoints should be an array of points (objects with and x and y)

Red triangle at 100, 100 example: shape(100, 100, [{x:-10, y:-10}, {x:10, y:-10}, {x:0, y:10}], "red");

text(txt, x, y, color="black", size=1, maxWidth=cw) - draws the string passed into txt. x,y is the top left of the text. Default color is black. Size sets the font size to size * 8. maxWidth is how many pixels text will go to the right before wrapping.

textWidth(txt, size=1) - returns how many pixels wide a sting will be.

Camera

The camera is just an object that will offset all graphics according to its values

camera - object used to offset graphics

.x - x offset of graphics

.y - y offset of graphics

.zoom - amount graphics are scaled by. Partial numbers work, but whole numbers look better

.angle - angle, in radians, the graphics are rotated by

centerCameraOn(x, y) - centers the x and y of the camera on the x and y passed in

moveCamera(x, y) - moves the camera taking into account the angle. Example: move camera "forwards" moveCamera(0, -1)

physics

Points, Circles, and Rectangles

3 different things can be used for physics (which is just collision detection), points, circles, and rectangles.

To have any of these, all you need is any object with the right properties.

point - any object with an x and a y

circle - any object with an x, y, and r (radius)

rectangle - any object with an x, y, w (width), and h (height)

Collision Detection

detect collision between and

returns true if there is a collision, returns false if no collision.

Misc.

dist(point, point) - returns the distance between two points

circleOnSideRect(circle, rect) - returns a number to indicate what side of a rectangle a circle is on.

return values: 0 = top, 1 = right, 2 = bottom, 3 = left

rectOnSideRect(rect, rect) - returns a number to indicate what side of a rectangle a rectangle is on.

audio

sounds - sounds defined in the audio variable will be loaded in during setup(framerate), and stored in sounds

play(sound) - plays a sound. Example: play(sounds.mySound)

setVolume(sound, volume) - sets the gain for a sound. 1 is the default volume, 0 is no sound

setType(sound, type) - sets the type for a sound. The type is used by the built in options for volume of sound effects and music. Type can either be "sfx" or "bgm"

stop(sound) - stops all instances of that sound

input

The input system is basically some arrays with booleans that correspond to keys or buttons

If there is no input function, call input code in the update function

Keys

keyDown - an array of booleans at the position of their corresponding key code. True when their key is held down.

To access a specific key, access the array at position [key code]

Up arrow key example: if( keyDown[ 38 ] ) { //code }

keyPress - same as keyDown, but only true the first frame a key is pressed

k - an object with key codes

Same example as above, but using k: if( keyDown[ k.UP ] ) { //code }

To see the full list that k has, enter k in the console or see the list here: a-z, 0-9, F1-F12, BACKTICK, MINUS, EQUALS, OPENSQUARE, ENDSQUARE, SEMICOLON, SINGLEQUOTE, BACKSLASH, COMMA, PERIOD, SLASH, ENTER, BACKSPACE, TAB, CAPSLOCK, SHIFT, CONTROL, ALT, META, LEFTBACKSLASH, ESCAPE, HOME, END, PAGEUP, PAGEDOWN, DELETE, INSERT, PAUSE, UP, DOWN, LEFT, RIGHT, CONTEXT, SPACE

Mouse

mouseDown - an array of booleans corresponding to mouse buttons. True when a mouse button is held down. To access a specific button, access the array at position [button code]

mousePress - same as mouseDown, but only true the first frame a button is pressed

mouse buttons - 0 = LMB, 1 = middle click, 2 = RMB

left click example: if( mousePress[ 0 ] ) { //code }

scroll - variable whose value is the scroll amount. One tick of a normal scroll wheel is 1 or -1, but things like laptop touchpads might return partial numbers.

mousePosition() - returns a point representing where the mouse is in the game.

mousePos - an object with an x and y. The mouse position ignoring the camera.

utils

rand(minimum, maximum) - returns a random whole number between the minimum and maximum (both inclusive)

radToDeg(radians) - pass in an angle in radians, returns the angle in degrees

degToRad(degrees) - pass in an angle in degrees, returns the angle in radians

pointTo(point, targetPoint) - returns the angle (in radians) something at point needs to be at to point towards targetPoint