Game Palette is a JavaScript library for making 2D games that
play on a canvas element in a web browser. It takes a simple
object-oriented approach that should be quick to pick up for anyone
who has done a little programming, and it does the hard parts of a
game for you: timing, drawing, animation, scrolling, keyboard
input, sound, loading, and saving. Everything in the library lives
in a single object, GAMEPALETTE, so it doesn't clash
with your own names. These are its main classes:
GAMEPALETTE.Engine:
usually you make just one of these for your game. It is given
the canvas element where your game appears, and it runs the
game: it calls your game logic, moves the camera, plays the
animations, and draws everything, at a steady speed.GAMEPALETTE.Image:
each of these holds a picture for your game, loaded from a file.
It can be a still picture, or a filmstrip of frames that the
engine plays as an animation.GAMEPALETTE.Sprite:
a sprite is what puts an image in the game. Sprites can be
moved about, turned, scaled, flipped, and faded. The image a
sprite shows can be swapped for another, and each sprite has a
renderer that decides
how it is drawn.GAMEPALETTE.KeyInput:
each of these is one control in your game, such as "jump",
bound to one or more keys. Your game can ask whether it is held
down, or have a function called when it is pressed or
released.GAMEPALETTE.Sound:
each of these holds a sound effect or a piece of music. One
sound can hold several recordings, one of which is picked at
random each time it plays, so repeated effects don't all sound
the same. Sounds can loop, overlap, cross-fade, and change
speed and pitch, and they can be grouped into categories whose
volumes are set together (think music volume and sound effect
volume).Add-ons, each in its own file, build on these, and you can
write your own (see Add-Ons). Two come with
Game Palette: GAMEPALETTE.LinkedSprite links sprites
into a hierarchy, such as the parts of a robot, so the others follow
the one you move, and GAMEPALETTE.CheckerboardMap draws
a whole scene from a grid of tiles.
The engine works by calling a logic function that you
write, over and over, a fixed number of times a second (30 unless
you choose otherwise; see
desiredFPS).
Each call is one step of the game: it reads the keys, moves the
sprites, and decides what happens. After each step, the engine
does the rest of the work and draws everything on the canvas. A
game is a series of logic modes, each with its own logic
function: one to load, one for the title screen, one to play, one
for game over, and so on (see
logicMode).
Each logic function is passed a state object, a place to
keep your game's variables, which the engine can save and load to
let players carry on a game later (see
saveState).
The engine keeps the game running at the speed you ask for,
whatever the speed of the player's screen. If the browser can't
keep up, the engine runs a few logic steps for each frame it draws,
to catch up, and if that isn't enough, it lets the game slow down
rather than jump ahead. Animations keep their own speed by the
clock, skipping frames if they must. You can watch how it's doing
with
actualLogicFPS
and
actualVisualFPS.
The Timing demo lets you change the number of steps a second and make the computer slow, to see all of this happen.
Sprites are placed in a 2D game world, each also at a depth,
z, which decides which
sprites are drawn in front of which. The camera, managed
by the engine, decides which part of the world is seen: it can be
moved and turned, and set to follow a sprite about its world
automatically (see
autoCameraSprite).
Turn on the engine's
perspectiveView,
and the depth also gives a pseudo-3D effect: the farther a sprite
is from the camera, the smaller it looks and the more slowly it
scrolls by, and the camera can even truck in and out among the
sprites. (The Parallax demo shows
this off.)
Remember, though, that this is ultimately a 2D game engine. All sprites are 2D pictures on individual flat planes that are never anything but exactly parallel to the camera.
The sprite renderers mentioned above are another feature of
Game Palette. Usually you'll use
GAMEPALETTE.singleImageRenderer,
the default, which draws the sprite's image once, in place. Others
are available, though.
GAMEPALETTE.tileFillRenderer
repeats the sprite's image endlessly in every direction, and
GAMEPALETTE.horizontalFillRenderer
and
GAMEPALETTE.verticalFillRenderer
repeat it endlessly in a row or a column, for backgrounds that
scroll for ever.
GAMEPALETTE.textRenderer
draws a line of text instead of an image. The CheckerboardMap
add-on provides
GAMEPALETTE.checkerboardTileRenderer, which paints an
entire scene with tiles placed according to a map. You can also
write your own renderers.
Images and sounds can also have triggers: functions of
yours called at a chosen frame of an animation or a chosen moment of
a sound, to play a footstep exactly as a foot lands, say (see the
Image's addTrigger
and the Sound's
addTrigger).
Game Palette runs in any up-to-date web browser, with nothing to install. Put your game on a web server, even one on your own computer, rather than opening its page straight from a file: browsers won't load sound files for a page opened from a file. The demos show each part of the library in a small working program, and are a good place to start.
The Game Palette download includes a
skeleton.html file,
which you can copy to start a new project. It is a complete,
working game page that does nothing yet: everything a game needs,
with comments where your code goes. In this chapter, we'll examine
its parts.
<!DOCTYPE html>
<html>
<head>
<title>Game Palette Skeleton</title>
<meta charset="utf-8">
<script type="text/javascript"
src="gamepalette.js"></script>
</head>
This, of course, sets up the HTML file, gives the page its
title, and loads the Game Palette library,
gamepalette.js. The src is a URL
relative to the page, so as written, gamepalette.js
must be in the same folder as the page; change it if you keep the
library somewhere else. If you use an add-on, load it with another
<script> tag after this one, since add-ons build
on the library:
<script type="text/javascript"
src="linkedsprite.js"></script>
<body>
<noscript>
This browser has JavaScript turned off; it is required to
use the Game Palette library
</noscript>
<canvas id="gameCanvas" width="1000" height="600"
style="width: 1000px; height: 600px;">
This browser does not support HTML5 canvas; it is required
to use the Game Palette library
</canvas>
This adds the canvas element, where the game appears, to the
page. The canvas must have an id attribute, which is
given to the engine when it's created; we use
"gameCanvas", but any name will do, as long as the two
match. The text inside the <noscript> and
<canvas> tags appears only if the browser can't
run the game, to say why. You can put anything else on the page
around the canvas, such as a title or instructions, as the demos
do.
It is very important to understand the difference between the
canvas size given by the width and height
attributes and the one given in the style attribute.
The latter,
style="width: 1000px; height: 600px;"
sets the size the canvas appears on the page, in this case in pixels. Whereas
width="1000" height="600"
sets the canvas's resolution, always in pixels: the space you,
the programmer, have to draw in, and what the engine's
canvasWidth
and canvasHeight
report. In this skeleton the two are the same, which gives a
one-to-one match between the pixels on the screen and the pixels you
work with in your code. But suppose, for example, you wanted to
copy the resolution of the Commodore 64 without the canvas being
tiny. Then you might use
<canvas id="gameCanvas" width="320" height="200"
style="width: 960px; height: 600px;">
and the browser gives you a nice low-resolution game in a large area by stretching your pixels to three times their size. The stretch doesn't have to be the same both ways. The Commodore 64's most colorful mode had 160 by 200 pixels, each twice as wide as it was tall, filling a 4:3 television screen, which you could copy with
<canvas id="gameCanvas" width="160" height="200"
style="width: 800px; height: 600px;">
and now you can program at 160 by 200 and let the browser worry
about stretching your graphics to fit the screen. Browsers blur
pixels as they stretch them; for crisp, blocky pixel art, add
image-rendering: pixelated; to the canvas's
style. (That setting is for the stretching of the
whole canvas; for images drawn scaled or turned within it, see the
engine's
smoothing.)
You may eventually want the canvas to resize itself to fit the
browser's window. The engine copes with that: it reads the
canvas's size afresh each frame, and keeps the camera's point at the
center. Set the canvas element's style sizes from your
own code when the window is resized, and its width and
height attributes too if you want the resolution to
change with it.
The Pixel art demo has a canvas of 160 by 100, stretched with sharp pixels, and it can fill the window, changing its width to suit.
The skeleton.html file goes on to the JavaScript
part.
<script type="text/javascript">
let engine = new GAMEPALETTE.Engine("gameCanvas");
First, we create an engine to run the game, with
new GAMEPALETTE.Engine.
It is given the id of the canvas tag. This script
comes after the canvas on the page, so the canvas already exists
when the engine looks for it.
The engine starts with sensible settings, but this is the place to change any you want to. For example,
engine.pauseOnWindowBlur = true;
engine.desiredFPS = 60;
would make the game pause whenever its window loses focus,
because the player has clicked outside the browser or gone to
another tab, and carry on when the window gets focus back (see
pauseOnWindowBlur),
and run the game at 60 steps a second instead of 30 (see
desiredFPS).
The engine keeps to that rate as best it can by itself, so once
it's set, you can forget about timing and concentrate on the game
itself.
engine.addLogicFunction("init", (s) =>
{
// Set up game assets here, tell Game Palette to
// display a load indicator bar, then go on to the
// "loadScreen" logic function
s.engine.startForegroundLoadIndicator();
s.engine.logicMode = "loadScreen";
});
Now we come to the first logic function.
addLogicFunction
adds a function you write to the engine under a name: the name of
its logic mode. Here the mode is "init". A new
engine always starts in "init", so this is the first
logic function called once the engine is started.
The idea is that the engine calls the logic function of the
current mode over and over, at the rate set by
desiredFPS, until a logic function changes the mode by
setting logicMode.
Then the new mode's function is called over and over, until the mode
is changed again, and so on. Setting logicMode doesn't
stop the function that sets it; the new mode's function is called
from the next step.
Every logic function is passed the state object, which we
call s. It's the same object every time, so it's the
place to keep your game's variables: whatever one call stores in it,
such as s.score = 0, the next call finds there, even in
a different logic function. It comes with s.engine
(and its short form, s.e) already set to the engine.
You could keep your variables in ordinary global variables instead,
but the state object has an advantage: the engine's
saveState and
loadState
functions can save everything in it and put it back, so players can
save a game and carry on later. (The functions here are arrow
functions, (s) => { ... }; ordinary
function(s) { ... } functions work just as well.)
The skeleton's "init" function is where you create
the game's assets, the
GAMEPALETTE.Image and
GAMEPALETTE.Sound
objects, since their files take time to download. For example,
s.playerImage = new GAMEPALETTE.Image(s.engine, "player.png",
32, 48);
s.jumpSound = new GAMEPALETTE.Sound(s.engine, "jump.mp3");
Then it calls
startForegroundLoadIndicator,
which shows a bar in the middle of the canvas that fills up as the
files arrive, and takes itself away when they all have. This is
very bare-bones, and you needn't use it; to draw your own loading
screen, use the engine's
loadProgress
to see how far loading has got. Since "init" only
needs to run once, it then changes the logic mode to
"loadScreen", so from the next step on, the
"loadScreen" function is called instead.
engine.addLogicFunction("loadScreen", (s) =>
{
// While in this mode, this function will be called
// repeatedly until all assets have been loaded
if(s.engine.loadProgress == 100)
{
s.engine.logicMode = "setupGame";
}
});
The "loadScreen" mode waits for the images and sounds
to finish loading. It's called over and over while the files
download (and the load indicator bar fills up), until
loadProgress
reaches 100. Then it changes the mode to
"setupGame". A file that fails to load (a misspelled
name, say) still counts as done, so loading always finishes; the
URLs of any that failed are in the engine's
loadErrors,
and in the browser's console, which is the first place to look if a
picture doesn't appear.
engine.addLogicFunction("setupGame", (s) =>
{
// Here, create all of the objects that will be used
// in the game, setting up everything that should be seen
// (and heard) once the game begins
s.engine.logicMode = "mainLoop";
});
In the "setupGame" mode, you create the
GAMEPALETTE.Sprite
objects, put them in place, and turn on the ones that should be seen
when the game begins. This is also the place to create the
GAMEPALETTE.KeyInput
objects for the game's controls, set the starting values of the
game's variables, and start any music. For example,
s.player = new GAMEPALETTE.Sprite(s.engine, s.playerImage,
0, 0);
s.player.isActive = true;
s.keyLeft = new GAMEPALETTE.KeyInput(s.engine,
["KeyA", "ArrowLeft"]);
s.keyRight = new GAMEPALETTE.KeyInput(s.engine,
["KeyD", "ArrowRight"]);
s.score = 0;
After this single call, the mode changes to
"mainLoop". Because the sprites are made here rather
than in "init", the images they show have loaded by the
time they first appear. And because setting up is a mode of its
own, a game can come back to it to start again, after a game over,
say.
engine.addLogicFunction("mainLoop", (s) =>
{
// Main game loop code goes here
});
The last logic function in the skeleton is the game's main loop.
It's called over and over, at the rate set by
desiredFPS, for as long as the game is being played,
and each call is one step of the game: check the controls, move the
sprites, see what has hit what, keep the score. Something
like
if(s.keyLeft.isPressed) s.player.x -= 4;
if(s.keyRight.isPressed) s.player.x += 4;
moves the player 4 pixels per step while a key is held, which at 30 steps a second is 120 pixels a second. When the game ends, the main loop changes the logic mode to another, such as a game over screen.
// Start the engine
engine.isRunning = true;
</script>
</body>
</html>
Finally, we start the engine and close the HTML file. A new
engine is stopped, so that you can add the logic functions first;
setting isRunning
to true starts it. Since the engine starts in the
"init" mode, the "init" logic function is
called straight away, and the whole process begins. Setting
isRunning to false later pauses the whole
game, sound and all, until it's set to true
again.
The skeleton.html file is meant as a simple
jumping-off place for your game. A full game is likely to have
many other modes, such as a title screen, an options screen, more
than one level, and a game over screen, depending on what your
project needs; add as many logic modes as you like. Do look at the
demos for ways to build on this simple
structure. Each follows it, and shows off one part of the library:
the Simple sprite control
demo is the skeleton with a sprite to fly around, and is the
best one to read first. The
Game flow demo is a complete little
game built the same way, with a title screen, pausing, a game over
screen, and a best score, each part in a logic mode of its
own.
A game's world is usually bigger than its canvas: a level that scrolls by as the player runs through it, or a map to explore. The camera decides which part of the world is seen. Think of your sprites as laid out on a huge table, and the canvas as the picture taken by a camera looking down at it. Move the camera, and a different part of the table is seen; turn it, and the picture turns. The engine looks after the camera, and draws every sprite where the camera sees it, so your game only has to say where things are in the world, and where the camera should look.
Every sprite has a position in the game world, its
x and
y, measured in pixels.
As on the canvas, x grows to the right and
y grows downwards, so a sprite moves up the
screen when its y gets smaller. Positions can be
negative, and fractions, and there is no edge to the world: the
numbers can go as far as you like.
The camera has a position too, its
cameraX and
cameraY: the point
in the world that is shown at the center of the canvas. Both
start at 0, so to begin with, a sprite at (0, 0) appears in the
middle of the canvas, a sprite at (100, 0) 100 pixels to the right
of the middle, and one at (0, -100) 100 pixels above it. So on a
1000 by 600 canvas, with the camera at (0, 0), the world from
x = -500 to 500 and y = -300 to 300 can be seen.
(If you'd rather that (0, 0) were at the top-left corner of the
canvas, as in canvas coordinates, start the camera at the middle
of the canvas instead:
engine.cameraX = engine.canvasWidth / 2 and
engine.cameraY = engine.canvasHeight / 2.)
To look at a different part of the world, change
cameraX and cameraY. Moving the camera to
the right makes everything on the canvas appear to slide to the
left, as when you turn your head. This logic function scrolls the
view with the arrow keys:
engine.addLogicFunction("mainLoop", (s) =>
{
if(s.keyLeft.isPressed) s.engine.cameraX -= 8;
if(s.keyRight.isPressed) s.engine.cameraX += 8;
if(s.keyUp.isPressed) s.engine.cameraY -= 8;
if(s.keyDown.isPressed) s.engine.cameraY += 8;
});
The camera can also be turned, with
cameraRotation,
measured in radians, as all angles in Game Palette are (a full turn
is 2 * Math.PI, about 6.28, and a quarter turn is
Math.PI / 2). The camera turns about the center of the
canvas, so the point it looks at stays put while the world turns
around it. Turning the camera clockwise makes the world appear to
turn the other way, counterclockwise:
// Rock the world gently, as on a ship's deck in a storm
// (s.time is a counter, increased by 1 every step)
s.time++;
s.engine.cameraRotation = Math.sin(s.time / 20) * 0.1;
Try moving and turning the camera in the Fill renderers demo, with the I, J, K, and L keys and U and O.
Most often, the camera should follow the player. You could set
cameraX and cameraY to the player's
position in every logic step, but the engine can do it for you, and
do it more smoothly. Set the engine's
autoCameraSprite
to the sprite to follow, and after each logic step the engine moves
the camera to keep that sprite in the middle of the canvas:
s.engine.autoCameraSprite = s.player;
Set it to null to stop following, and the camera
stays where it is. Set it to an array of sprites, and the camera
follows the point midway between them, which keeps two players in
view together.
A camera fixed tightly on the player can feel stiff, as every
small movement shakes the whole view.
autoCameraLooseness
loosens it. At 0, the camera stays exactly on the sprite. At 1,
each step it moves half the way to the sprite; at 3, a quarter of
the way; and so on. A loose camera lags behind when the sprite sets
off, catches up as it goes, and glides to a stop when the sprite
stops. Values from about 2 to 10 feel good in most games.
The sprite needn't be kept in the very middle. In a game where
the player runs to the right, it's better to see more of what's
ahead than what's behind.
autoCameraCenterOffsetX
and
autoCameraCenterOffsetY
move the sprite away from the center: negative values move it left
or up, and positive ones right or down.
// Keep the runner 300 pixels left of the middle, and a little low
s.engine.autoCameraCenterOffsetX = -300;
s.engine.autoCameraCenterOffsetY = 100;
Finally, a level has edges, and the camera shouldn't show what's
beyond them. The four limits,
autoCameraLeftLimit,
autoCameraRightLimit,
autoCameraTopLimit,
and
autoCameraBottomLimit,
stop the camera at the edges of the world. They limit where the
camera looks, the center of the view, so allow for half the
canvas. For a level running from x = 0 to x = 4000, on a canvas
1000 pixels wide, the center of the view must stay between 500 and
3500:
s.engine.autoCameraLeftLimit = s.engine.canvasWidth / 2;
s.engine.autoCameraRightLimit = 4000 - (s.engine.canvasWidth / 2);
Now the camera follows the player through the middle of the
level, but when the player runs to the very end, the camera stops
at the edge and the player runs on towards the side of the canvas.
Leave a limit at null, its starting value, for no limit
on that side. The Parallax demo
follows its UFO with a loose camera kept within limits, and the
Camera demo tries each setting in
turn: a manual camera, tight and loose following, looking ahead with
the center offsets, following two sprites at once, and limits off
and on.
Every sprite also has a depth,
z, which says how far
away it is. A larger z is farther away, so sprites
with a larger z are drawn first, and nearer sprites are
drawn over them. Give the backdrop a large z, the
scenery a smaller one, and the player and the things in front of the
player smaller still:
s.sky = new GAMEPALETTE.Sprite(s.engine, s.skyImage, 0, 0, 100);
s.house = new GAMEPALETTE.Sprite(s.engine, s.houseImage, 400, 0, 10);
s.player = new GAMEPALETTE.Sprite(s.engine, s.playerImage, 0, 0, 0);
s.bush = new GAMEPALETTE.Sprite(s.engine, s.bushImage, 200, 0, -10);
Here the player can walk behind the bush but in front of the
house. Sprites with the same z are drawn in the order
they were made active, the latest on top. Changing a sprite's
z moves it in front of or behind the others straight
away, so a character can step behind a pillar and out again. Only
the order matters, so the numbers can be whatever is convenient.
So far, depth only decides what is drawn in front of what. Turn
on the engine's
perspectiveView,
and it also decides how big things look and how fast they move, as
in a real camera. Faraway sprites are drawn smaller, and, as the
camera moves, they scroll by more slowly than nearby ones, which
gives the scene a feeling of depth, called parallax: think of
the view from a train window, where the fence rushes past while the
hills barely move.
With perspective on, a sprite at depth z is drawn
at this many times its size:
focalLength / (z - cameraZ + focalLength)
That looks complicated, but with the camera in its starting
place (cameraZ at 0) and the engine's
focalLength at
its starting value of 1000, it works out like this:
z = 0 is drawn at its normal size,
and moves across the canvas exactly as fast as the camera
moves;z = 1000 is drawn at half size, and
scrolls by at half the speed;z = 3000 is drawn at a quarter size,
and scrolls at a quarter of the speed;z = -500, in front of the others, is
drawn at twice its size, and rushes by twice as fast.The focal length is how far the camera stands back from the
sprites at cameraZ. A short focal length, such as 300,
gives a deep, dramatic view where size and speed change quickly with
depth; a long one, such as 3000, a flatter view. Choose one that
suits your scenery, then choose depths for your layers. For
example, a scene with mountains, hills, a road and a fence:
s.engine.perspectiveView = true;
s.engine.focalLength = 1000;
s.mountains = new GAMEPALETTE.Sprite(s.engine, s.mountainsImage,
0, 0, 4000);
s.hills = new GAMEPALETTE.Sprite(s.engine, s.hillsImage, 0, 100, 1500);
s.road = new GAMEPALETTE.Sprite(s.engine, s.roadImage, 0, 200, 0);
s.fence = new GAMEPALETTE.Sprite(s.engine, s.fenceImage, 0, 260, -300);
Things to keep in mind with perspective:
scaleX and
scaleY: scaling a
sprite at z = 1000 by 2 brings it back to its full
size, while it still scrolls at half speed. The Parallax demo's
moon is scaled up 31 times to make up for being at
z = 30000.y by trying
it, or work it out with the formula, as the
Parallax demo does.cameraZ, moves
the camera forward and back among the sprites, like a film camera
on a dolly: increase it to move in, and everything grows, the near
things fastest. Sprites the camera has passed (with a
z not far enough beyond cameraZ) aren't
drawn.The Parallax demo shows all of this: fly its UFO with the arrow keys, move it in depth with Z and X, move the camera in and out with I and K, and change the focal length with J and L. With perspective off, as it is to begin with, sprites are always drawn at their own size, whatever their depth.
Sometimes you need to know where a point in the world appears on
the canvas, or which point of the world is at a place on the canvas.
The engine's
worldToCanvas
and
canvasToWorld
work it out, allowing for the camera's position and rotation, and
for perspective. Each returns an object with x and
y properties, or null for a point that
isn't drawn (behind the camera, with perspective on). For example,
canvasToWorld turns a mouse click into a point in the
game world (see Mouse and touch), and
worldToCanvas can tell whether a sprite is on the
screen:
let point = s.engine.worldToCanvas(s.enemy.x, s.enemy.y, s.enemy.z);
let onScreen = point !== null &&
point.x >= 0 && point.y >= 0 &&
point.x < s.engine.canvasWidth &&
point.y < s.engine.canvasHeight;
The Mouse and touch demo shows
canvasToWorld at work, even with the camera
turned.
Some things should stay put on the canvas whatever the camera does: the sky, the score, the number of lives left. For these, the engine has two drawing functions of your own that it calls every time it draws a frame:
backgroundFunction,
called first, before any sprite is drawn, for whatever is behind
everything;foregroundFunction,
called last, after every sprite is drawn, for whatever is in front
of everything.Each is called with two arguments: the canvas's drawing context
(the same as engine.cc),
to draw with, and the camera's rotation, in case the drawing should
turn with the world. They draw in canvas coordinates, with (0, 0)
at the top-left corner of the canvas, using the browser's own canvas
drawing functions, such as fillRect and
fillText. The camera doesn't move them.
s.engine.backgroundFunction = (cc, cameraRotation) =>
{
// A plain blue sky
cc.fillStyle = "rgb(100, 160, 255)";
cc.fillRect(0, 0, s.engine.canvasWidth, s.engine.canvasHeight);
};
s.engine.foregroundFunction = (cc, cameraRotation) =>
{
// The score, in the top-left corner
cc.fillStyle = "white";
cc.font = "24px sans-serif";
cc.textBaseline = "top";
cc.fillText("Score: " + s.score, 10, 10);
};
Like renderers, they should only draw: change the game in your logic functions, and let these show it. The canvas is not cleared between frames, so unless sprites cover the whole canvas, have the background function paint all of it, as here; otherwise each frame is drawn over the last, leaving trails. The Parallax demo's background function draws a sky whose stars turn with the camera, and its foreground function shows the camera's settings. (While the load indicator is showing, it uses the foreground function, so set yours once loading is done.)
Every sprite has a renderer: the function that draws it. Most sprites simply show their image, and for them the default renderer does the job, so you may never need to think about renderers at all. But by giving a sprite a different renderer, you can have it draw its image repeated across the whole view, draw a line of text, draw a map of tiles, or draw anything else at all that you can draw on a canvas. Whatever the renderer draws still belongs to the sprite: it moves, turns, scales, and fades with the sprite, is seen through the camera, and is drawn in front of or behind other sprites according to its depth.
A sprite's renderer is its
renderer
property, which can be given as the sixth argument of the
constructor or set at any
time afterwards. Some renderers need extra information, such as the
text to write, which goes in the sprite's
rendererParameter,
the seventh argument. The renderers that come with Game Palette
are:
GAMEPALETTE.singleImageRenderer,
the default, which draws the current frame of the sprite's
image;GAMEPALETTE.textRenderer,
which writes a line of text;GAMEPALETTE.tileFillRenderer,
GAMEPALETTE.horizontalFillRenderer,
and
GAMEPALETTE.verticalFillRenderer,
which repeat the sprite's image endlessly;GAMEPALETTE.checkerboardTileRenderer, from the
CheckerboardMap add-on, which draws a map of tiles (see
CheckerboardMap).Notice that you give the renderer itself, the function, without
calling it: GAMEPALETTE.textRenderer, not
GAMEPALETTE.textRenderer(). The engine calls it each
time it draws the sprite.
The text renderer writes text in the game world, where a sprite
would be. Its rendererParameter is an object giving the
text, and optionally its font and
color, in the same form as CSS. The sprite needs no
image, so give null for that. The text starts at the
sprite's position, which is at the left end of the line the letters
sit on.
Text sprites are good for anything written in the world that should move with it: a name over a character's head, a sign, or the points scored when a coin is collected, which rise and fade away:
// When a coin is collected, at the coin's position
s.points = new GAMEPALETTE.Sprite(s.engine, null, s.coin.x, s.coin.y,
-1, GAMEPALETTE.textRenderer,
{text: "+100", font: "bold 20px serif",
color: "gold"});
s.points.isActive = true;
// In the main loop: rise and fade, then go
if(s.points.isActive) {
s.points.y -= 2;
s.points.alpha -= 0.03;
if(s.points.alpha == 0) s.points.isActive = false;
}
To change what a text sprite says, change its
rendererParameter's text:
s.label.rendererParameter.text = "Open";. For text
that should stay in one place on the screen whatever the camera
does, such as the score, draw it in the engine's foreground function
instead (see Things the camera doesn't
move).
A game that scrolls needs a background that goes on as far as the player can travel. You could line up dozens of sprites side by side, but the fill renderers do it with one sprite. Each draws the sprite's image over and over, edge to edge, as far as the view reaches, so there's always background however far the camera goes, and the engine only draws the copies that can be seen. Make the image so that its left edge matches its right edge, and its top matches its bottom, and the joins won't show.
GAMEPALETTE.tileFillRenderer repeats the image
in every direction, filling the whole view: grass, water, a starry
sky, the floor of a room seen from above.GAMEPALETTE.horizontalFillRenderer repeats it in
a single row, endlessly to the left and right: the ground, a road,
a line of distant hills.GAMEPALETTE.verticalFillRenderer repeats it in a
single column, endlessly up and down: a ladder, a waterfall, the
wall of a tower.The row or column passes through the sprite: one copy of the image is exactly where the default renderer would draw it, and the rest are lined up with that one. So to put the ground at the bottom of a side-scrolling level, place the sprite where one piece of ground should be:
s.ground = new GAMEPALETTE.Sprite(s.engine, s.groundImage, 0, 250, 50,
GAMEPALETTE.horizontalFillRenderer);
s.ground.isActive = true;
Because a fill-rendered sprite is still a sprite, everything in the last chapter applies to it. Moving the sprite slides the pattern along; turning or scaling the sprite turns or scales the whole pattern; and with perspective on, a pattern far away is small and scrolls slowly, which makes layers of endless scenery easy. The Fill renderers demo lets you switch between the three with the 1, 2, and 3 keys, and move, turn, and zoom the sprite and the camera to see how they behave.
When none of the renderers draws what you want, write your own.
A renderer is a function that the engine calls with two arguments,
the engine and the sprite, every time it draws the sprite. It draws
with the engine's canvas drawing context,
engine.cc, using the
browser's canvas drawing functions.
What makes renderers easy to write is that the engine prepares
the canvas before calling one: it moves, turns, and scales the
canvas's coordinates to match the camera and the sprite. So a
renderer draws as though the sprite were sitting still, unturned, at
the origin, and the engine takes care of the rest. For a sprite
with an image, (0, 0) is the top-left corner of where its image
goes, and for a sprite without one, (0, 0) is the sprite's position.
The canvas's transparency is also set to the sprite's
alpha, and any
setting the renderer changes, such as the fill color, is put back
afterwards.
This renderer draws a ball, with no image at all. Its color and
size come from the sprite's rendererParameter, so one
renderer can draw many different balls:
function ballRenderer(engine, sprite)
{
let ball = sprite.rendererParameter;
engine.cc.fillStyle = ball.color;
engine.cc.beginPath();
engine.cc.arc(0, 0, ball.radius, 0, 2 * Math.PI);
engine.cc.fill();
}
s.redBall = new GAMEPALETTE.Sprite(s.engine, null, 0, 0, 0,
ballRenderer,
{color: "red", radius: 20});
s.blueBall = new GAMEPALETTE.Sprite(s.engine, null, 100, 0, 0,
ballRenderer,
{color: "blue", radius: 35});
A renderer can also draw the sprite's image, together with
something more. The image's
drawFrame
function draws one of its frames, and draws nothing until the image
has loaded. This renderer draws the sprite's image with a health
bar above it. Its rendererParameter is the enemy's own
record, so the bar always shows the enemy's latest health:
function healthBarRenderer(engine, sprite)
{
let image = sprite.image;
let enemy = sprite.rendererParameter;
image.drawFrame(sprite.frame);
engine.cc.fillStyle = "red";
engine.cc.fillRect(0, -10, image.imageWidth, 4);
engine.cc.fillStyle = "lime";
engine.cc.fillRect(0, -10,
image.imageWidth * enemy.health / enemy.maxHealth,
4);
}
s.troll = {health: 50, maxHealth: 50};
s.trollSprite = new GAMEPALETTE.Sprite(s.engine, s.trollImage, 300, 0,
0, healthBarRenderer, s.troll);
A few rules make for good renderers:
visibleArea
gives.saveState, a
sprite's renderer is saved by name, so give a renderer of your own
a name with the engine's
addSaveName:
s.engine.addSaveName("ballRenderer", ballRenderer).A renderer you use in more than one game can be put in an add-on
(see Add-Ons). The reference section,
Writing a renderer,
gives the details, and the
Custom renderers demo has
several to read: shapes with no image, a health bar, a shadow, and
an endless grid that uses visibleArea.
Sound brings a game to life: music to set the mood, and effects
that tell the player what's happening, a jump, a coin, a crash.
Each sound in a game is a
GAMEPALETTE.Sound, made
from a sound file. Game Palette plays sounds with the browser's Web
Audio system, so they start without delay and can be mixed
freely. The Sound demo is a mixing
desk for trying every feature in this chapter; it shows the exact
code for each thing you do.
Make your sounds in the "init" logic function, with
the images, so that the loading screen waits for them too:
s.jumpSound = new GAMEPALETTE.Sound(s.engine, "jump.mp3");
The file name is a URL, relative to the page, just like an image's. Two things are worth knowing about sound files in browsers:
[["jump.ogg", "jump.mp3"]]. The demos do this.A sound that plays very often, such as a footstep or a hit, gets tiresome when it's exactly the same every time. So a sound can hold several recordings of the same thing, given as an array, and each time it plays, it picks one at random:
s.stepSound = new GAMEPALETTE.Sound(s.engine,
["step1.mp3", "step2.mp3", "step3.mp3"]);
(With two formats as well, each recording is its own inner array:
[["step1.ogg", "step1.mp3"], ["step2.ogg", "step2.mp3"]].)
A sound file that can't be found or played shows in the browser's
console, and its URL in the engine's
loadErrors; the
game carries on without it.
To play a sound, call its
play function. To stop
it, call stop. A
sound's isPlaying
tells you whether it's still playing.
s.keyJump.keyDownFunction = () =>
{
s.player.y -= 100;
s.jumpSound.play();
};
What happens when a sound is played while it's still playing from before is up to you:
allowSimultaneousPlay
set to true, each play starts a new one alongside the
others, so they overlap, as rapid gunfire or a shower of coins
should.loopSound set to
true, the sound plays over and over until it's
stopped, which is how music and background noises (wind, rain, an
engine's hum) are played. Playing it again while it plays does
nothing.
s.music = new GAMEPALETTE.Sound(s.engine, [["theme.ogg", "theme.mp3"]],
"music");
s.music.loopSound = true;
s.coinSound = new GAMEPALETTE.Sound(s.engine, "coin.mp3", "effects");
s.coinSound.allowSimultaneousPlay = true;
Set these when you make the sound: they can't be changed while
it's playing, and a sound can't both loop and overlap itself. A
looping recording made to loop seamlessly loops without a gap. One
that doesn't quite loop can be smoothed over by fading each time
round into the next: set the sound's
simultaneousCrossFadeRate
to the length of the fade in seconds, such as 0.5. (That setting
also sets how long a sound that restarts itself takes to fade out
the old playing.)
Browsers don't let a web page make any sound until the player has done something on the page: clicked, tapped, or pressed a key. This stops pages blaring out at you as they open. Until then, Game Palette keeps any sound you play waiting, and starts it the moment the player does something, so nothing is lost; the music for a title screen, for example, starts as soon as the player presses a key. That's one good reason for a game to start with a title screen saying "Press any key to start" (see Press any key).
Sound also plays only while the engine is running. When the engine is stopped, all sound pauses, and when it starts again, the sound carries on where it left off, so pausing the game pauses its sound too.
Each sound has its own
volume, from 0
(silent) to 1 (full volume), for balancing it against the others: a
loud recording can be turned down to sit well with the rest.
Players often want to set the volume of the music and of the
sound effects separately, so sounds can be grouped into
categories, each with its own volume. A sound's category is
a name of your choosing, given as the third argument when it's made
(as for the music and coin above), or set with its
category
property. The engine sets the volume of a whole category with
setCategoryVolume,
and of everything at once with its
masterVolume:
s.engine.setCategoryVolume("music", 0.5); // music at half volume
s.engine.setCategoryVolume("effects", 1); // effects at full
s.engine.masterVolume = 0.8; // everything a bit lower
The volumes multiply together, so the coin sound above plays at
its own volume, times the effects volume, times the master volume.
A category exists once a sound belongs to it, and it starts at full
volume, so set a category's volume after making its sounds (setting
the volume of a category that has no sounds is an error). The
engine's
soundCategories
lists the categories there are, and
getCategoryVolume
tells you one's volume. Keep the player's choices of volume
yourself (in localStorage, say), since a saved game
doesn't hold them.
Changing a volume all at once can sound abrupt. Fades change it smoothly over a time you choose, in seconds:
fadeVolume,fadeCategoryVolume
for a category,fadeMasterVolume
for everything.A fade happens by itself while the game goes on, and a new fade takes over from one already under way. Fading a sound to 0 doesn't stop it; it plays on silently until it's stopped. For example, to change from the level music to the boss music, fading one out as the other fades in:
// When the boss appears
s.levelMusic.fadeVolume(0, 2);
s.bossMusic.volume = 0;
s.bossMusic.play();
s.bossMusic.fadeVolume(1, 2);
// In the main loop: once the level music is silent, stop it, and
// set its volume back ready for next time
if(s.levelMusic.isPlaying && s.levelMusic.volume == 0) {
s.levelMusic.stop();
s.levelMusic.volume = 1;
}
Fades follow the engine's clock, so they pause when the engine is stopped.
A sound's
playbackRate
sets how fast it plays: 1 is normal, 2 twice as fast, 0.5 half as
fast. As with a record played at the wrong speed, faster is also
higher, and slower lower. Change it as the game goes on, and a car
engine revs up as the car speeds up:
// In the main loop: an engine hum that rises with the car's speed
s.engineSound.playbackRate = 0.8 + (s.carSpeed / 20);
fadePlaybackRate
changes it smoothly over a time, for a siren winding up or a tape
slowing to a stop.
Like the random choice of recordings, a little random change of
pitch keeps a repeated sound from sounding mechanical. Set a
sound's
pitchVariation
to a number of semitones (the steps of a musical scale), and each
time it plays, it's raised or lowered by a random amount up to
that. One or two semitones is usually plenty.
s.stepSound.pitchVariation = 1.5;
A sound's isPaused
pauses it where it is, and unpausing carries it on from there: for
example, to hold the music while a message is shown. This is
separate from the engine stopping, so a sound you've paused stays
paused when the engine starts again.
A sound that won't be needed again, such as the music of a level
that's over, can be removed with its
deleteSelf,
which stops it and takes it out of the game.
When a game is saved with
saveState, each
sound's settings are saved, and music that was looping starts again
when the game is loaded. Other sounds partway through playing
aren't saved, which is rarely missed.
Games are full of things that must happen at just the right moment: a footstep sound exactly as a foot lands, an arrow let fly as the bowstring is released, the next piece of music starting the instant the last one ends. You could work out when those moments come by counting steps in your logic functions, but it's fiddly, and goes wrong as soon as the timing changes. A trigger does it for you: it's a function of yours that the engine calls when an animation reaches a chosen frame, or a sound reaches a chosen moment. Images and sounds both have triggers.
An image's
addTrigger adds
a trigger to one of its frames. Whenever the animation of any
sprite showing the image reaches that frame, the engine calls the
trigger, passing it the sprite that reached the frame, and the
frame's number. Frames are counted from 0. Suppose a walking
animation has 8 frames, and the feet land on frames 1 and 5:
s.walkImage = new GAMEPALETTE.Image(s.engine, "walk.png",
48, 64, 8, 12, 24, 64);
s.walkImage.addTrigger(1, (sprite) => s.stepSound.play());
s.walkImage.addTrigger(5, (sprite) => s.stepSound.play());
Now every sprite that walks with this image makes footsteps in
time with its feet, however fast it walks and however many of them
there are, with no more code anywhere else. Set up triggers when you
make the image, in your "init" logic function.
Because the trigger is told which sprite reached the frame, one trigger can serve many sprites. This one makes any archer that reaches the release frame of its shooting animation fire an arrow from where it stands:
s.shootImage.addTrigger(6, (archer) =>
{
s.arrows.push(new GAMEPALETTE.Sprite(s.engine, s.arrowImage,
archer.x, archer.y - 30));
s.arrows[s.arrows.length - 1].isActive = true;
});
Triggers are dependable:
frameRate),
so a footstep is never missed.frame or
image yourself
doesn't fire a trigger; only the animation moving on to a frame
does.An image's
getTriggers
lists its triggers, and
removeTrigger
removes one, given the number that addTrigger
returned.
Hand in hand with triggers goes an image's
onComplete,
which says what a sprite does when its animation runs past the last
frame. It can be:
Together with triggers, this lets animations run a whole sequence by themselves. For example, a sword attack that checks for a hit at the moment the blade swings through, and goes back to standing when it's done:
s.standImage = new GAMEPALETTE.Image(s.engine, "stand.png",
64, 64, 4, 6, 32, 64);
// The attack has 9 frames, and goes back to standing at the end
s.attackImage = new GAMEPALETTE.Image(s.engine, "attack.png",
64, 64, 9, 18, 32, 64, 0);
s.attackImage.onComplete = s.standImage;
s.attackImage.addTrigger(4, (knight) =>
{
if(Math.abs(s.troll.x - knight.x) < 60) s.troll.health -= 10;
});
// In the main loop: attack when the key is pressed
if(s.keyAttack.isPressed && s.knight.image === s.standImage) {
s.knight.image = s.attackImage;
}
And an explosion that plays once, then removes itself:
s.boomImage.onComplete = (sprite) => { sprite.isActive = false; };
The Animation demo puts these together: a knight whose walk has footstep triggers, whose attack has a trigger for the blow and returns to standing when it ends, and an explosion that turns itself off.
A sound's
addTrigger adds
a trigger at a time in the sound, in seconds from its start.
Whenever the sound, playing, reaches that time, the engine calls the
trigger (with no arguments). Use it to time things to a sound: flash
the lights on the crash of a cymbal, show each line of a speech as
it's spoken, or, as here, start the music's main loop as soon as its
introduction ends:
// The introduction is 12.5 seconds long
s.intro = new GAMEPALETTE.Sound(s.engine, "intro.mp3", "music");
s.theme = new GAMEPALETTE.Sound(s.engine, "theme.mp3", "music");
s.theme.loopSound = true;
s.intro.addTrigger(12.5, () => s.theme.play());
A few things to know about sound triggers:
playbackRate),
it comes sooner.A sound's
removeTrigger
removes one of its triggers. The
Sound triggers demo starts its
music's loop from a trigger at the end of the introduction, and
flashes lights from triggers on the beat.
Triggers are called when the engine reaches the moment, not as part of a logic step: animation triggers just before a frame is drawn, after that frame's logic steps, and sound triggers whenever the engine checks the sounds. A trigger can do anything a logic function can, but it's best to keep triggers short and simple: play a sound, start an animation, or make a note in the state object for the logic function to act on in its next step.
// The trigger only notes what happened...
s.attackImage.addTrigger(4, (knight) => { s.swordSwung = true; });
// ...and the main loop deals with it
if(s.swordSwung) {
s.swordSwung = false;
checkForHits(s);
}
Triggers belong to images and sounds, which a saved game doesn't copy: when a game is loaded, it uses the game's own images and sounds again, triggers and all. So triggers keep working after a load without any extra work.
A game needs to know what the player is doing. In Game Palette,
each of the game's controls, "left", "right", "jump", "fire", is a
GAMEPALETTE.KeyInput,
tied to one or more keys of the keyboard. Your game asks the key
input whether it's held down, or has it call a function when it's
pressed, and doesn't have to deal with the browser's keyboard events
itself.
Make the key inputs in your "setupGame" logic
function, naming the keys each uses:
s.keyLeft = new GAMEPALETTE.KeyInput(s.engine, ["KeyA", "ArrowLeft"]);
s.keyRight = new GAMEPALETTE.KeyInput(s.engine, ["KeyD", "ArrowRight"]);
s.keyJump = new GAMEPALETTE.KeyInput(s.engine, "Space");
Each key is named by its key code: "KeyA" to
"KeyZ" for the letters, "Digit0" to
"Digit9" for the numbers above them,
"ArrowUp", "ArrowDown",
"ArrowLeft", and "ArrowRight" for the
arrows, and names such as "Space",
"Enter", "ShiftLeft", and
"Escape" for the rest. To find the code of any key,
press it on the key code
utility page.
A key code names a key by its place on the keyboard, not by the
letter printed on it. That's what a game wants: "KeyW",
"KeyA", "KeyS", and "KeyD"
are the four keys in the shape of arrows on the left of the
keyboard, wherever the player lives and whatever letters their
keyboard has. Shift and Caps Lock make no difference either.
Give a key input an array of codes, as for left and right above, and any of those keys works the control, so players can use whichever keys they like. Giving players the arrow keys and WASD both is a good habit.
A key input's
isPressed is
true while any of its keys is held down. Check it in
your main loop for things that go on for as long as a key is held,
such as walking:
engine.addLogicFunction("mainLoop", (s) =>
{
if(s.keyLeft.isPressed) s.player.x -= 5;
if(s.keyRight.isPressed) s.player.x += 5;
});
Since the logic function runs a steady number of times a second, the player moves at a steady speed: here, 5 pixels a step. The Simple sprite control demo moves, turns, and scales its sprite this way.
One thing to watch for, in games where the player can move in any direction: holding up and right together moves the player 5 pixels up and 5 pixels right, which is about 7 pixels diagonally, faster than in a straight line. To move at the same speed in every direction, work out the direction first, then scale it to the speed:
let dx = (s.keyRight.isPressed ? 1 : 0) - (s.keyLeft.isPressed ? 1 : 0);
let dy = (s.keyDown.isPressed ? 1 : 0) - (s.keyUp.isPressed ? 1 : 0);
let length = Math.hypot(dx, dy);
if(length > 0) {
s.player.x += 5 * dx / length;
s.player.y += 5 * dy / length;
}
Other things should happen once each time a key is pressed, not
for as long as it's held: a jump, a shot, a pause. For these, give
the key input a
keyDownFunction,
which the engine calls the moment the key goes down, once each time
it's pressed. Holding the key down doesn't call it again. There's
a keyUpFunction
too, called when the key comes back up.
s.keyFire = new GAMEPALETTE.KeyInput(s.engine, ["Space", "KeyF"]);
s.keyFire.keyDownFunction = () =>
{
s.laserSound.play();
s.shotsFired++;
};
Key functions are called straight away, whatever logic mode the game is in, and even while the engine is stopped. That's just right for a pause key, which must work while the game is paused:
s.keyPause = new GAMEPALETTE.KeyInput(s.engine, ["KeyP", "Escape"]);
s.keyPause.keyDownFunction = () =>
{
s.engine.isRunning = !s.engine.isRunning;
};
But it means that a key function for the game itself, like the fire key above, also works on the title screen or the game over screen, or while the game is paused. If it shouldn't, have it check first:
s.keyFire.keyDownFunction = () =>
{
if(s.engine.logicMode != "mainLoop" || !s.engine.isRunning) return;
s.laserSound.play();
s.shotsFired++;
};
Another way to act once per press, all within the main loop, is to remember whether the key was held in the last step, and act only when it has just gone down:
if(s.keyJump.isPressed && !s.jumpWasPressed) jump(s);
s.jumpWasPressed = s.keyJump.isPressed;
This keeps everything in one place, and only happens while the
main loop runs. A tap so quick that the key goes down and up between
two steps can be missed, though, which can't happen with a
keyDownFunction.
Many games start with a title screen that waits for the player to
press a key. GAMEPALETTE.anyKey is an array of the
codes of nearly every key, ready for this. Here, a logic mode sets
up the title screen, with a key input for every key, and then waits
in the "titleScreen" mode; the key function starts the
game, and removes the key input, which isn't needed any more:
engine.addLogicFunction("setupTitle", (s) =>
{
// Show the title's sprites, start its music, and so on, then
// wait for a key
s.keyStart = new GAMEPALETTE.KeyInput(s.engine, GAMEPALETTE.anyKey);
s.keyStart.keyDownFunction = () =>
{
s.keyStart.deleteSelf();
s.engine.logicMode = "setupGame";
};
s.engine.logicMode = "titleScreen";
});
engine.addLogicFunction("titleScreen", (s) =>
{
// Nothing to do but wait (or animate the title)
});
The "loadScreen" mode would then go on to
"setupTitle" rather than straight to
"setupGame". The key that starts the game doesn't also
work the game's own controls, since they're made afterwards, in
"setupGame".
A key press is also what browsers wait for before they let a page make sound (see When sound can start), so after a title screen, the game's sound is sure to play. The Game flow demo starts with a title screen like this.
A key input's key
can be changed at any time, which lets players choose their own
keys:
s.keyJump.key = ["KeyW", "ArrowUp"];
A control that's no longer needed can be removed with its
deleteSelf.
Several key inputs can share a key, and all of them respond to it,
so you can, for example, have one key input for each of the game's
controls and another of all the keys at once.
The Keyboard demo shows the
ideas in this chapter: controls with two keys each, a fire key
counted both by its keyDownFunction and by
isPressed, movement at the same speed in every
direction beside movement that's faster on the diagonals, and
choosing new keys.
A game is part of a web page, and the engine takes care to keep the two from getting in each other's way:
pauseOnWindowBlur
to true to pause the game then, too.Game Palette doesn't handle the mouse or touch screens itself yet
(the key inputs' area properties are there for when it does), but a
game can listen for them in the usual way of web pages, with the
canvas's addEventListener. The pointerdown
event comes from a mouse click, a tap, or a pen alike. Two things
make it fit in with the rest of the game:
canvasToWorld
turns it into a point in the game world, allowing for the
camera.
// In "setupGame": note where the player clicks or taps
let canvas = s.engine.cc.canvas;
canvas.addEventListener("pointerdown", (event) =>
{
let x = event.offsetX * canvas.width / canvas.clientWidth;
let y = event.offsetY * canvas.height / canvas.clientHeight;
s.target = s.engine.canvasToWorld(x, y);
});
// In the main loop: walk towards the last place clicked
if(s.target != null) {
let dx = s.target.x - s.player.x;
let dy = s.target.y - s.player.y;
let distance = Math.hypot(dx, dy);
if(distance <= 5) {
s.target = null;
} else {
s.player.x += 5 * dx / distance;
s.player.y += 5 * dy / distance;
}
}
The Mouse and touch demo is this example, working.
An add-on is an extra JavaScript file that adds to Game Palette:
new classes, new renderers, or new things for the engine to do
each step. The core library, gamepalette.js, holds
what nearly every game needs; add-ons hold what only some games
need, so that the others don't have to load it. Two add-ons come
with Game Palette, and you can write your own.
Load an add-on with its own <script> tag,
after the one that loads gamepalette.js, since an
add-on builds on the library:
<script type="text/javascript"
src="gamepalette.js"></script>
<script type="text/javascript"
src="linkedsprite.js"></script>
Loaded the other way round, the add-on stops with an error in the
browser's console saying which file to load first. An add-on that
needs another add-on says so the same way. Once loaded, an add-on's
classes and functions are part of GAMEPALETTE, just
like the library's own, and they work with everything else: their
objects can be kept in the state object and saved with
saveState, for
example. To check from your game whether an add-on is loaded, use
GAMEPALETTE.hasAddOn.
The LinkedSprite add-on, linkedsprite.js, joins
sprites together into a hierarchy, such as the wheels, body, arms,
and head of a robot, so that you move only the one at the top (the
root) and the others follow it. Each linked sprite keeps its
place relative to its parent, turning with it, but follows with a
delay, its drag,
and within limits
you set, so the parts of
the robot sway and lag behind as it moves, as though loosely joined.
Each part can have parts of its own. Your logic function moves the
root sprite and then calls the root's
animateChildren
function once per step, which moves all the rest. The
Linked sprites demo shows it
in action: a robot whose parts follow its wheels.
See linkedsprite.html
for the full description of the add-on.
The CheckerboardMap add-on, checkerboardmap.js,
draws a whole scene from a grid of tiles: a gameboard, a maze, or
the floor and walls of a level, laid out like the squares of a
checkerboard. All the pictures of the tiles are kept in one
GAMEPALETTE.Image, one
row per kind of tile, and a tile can be animated, with its frames
along its row. A
GAMEPALETTE.CheckerboardMap holds the
tiles' image, a description of each kind of tile (with room for
the game's own details, such as whether it's a wall), and a map
saying which kind of tile goes in each square. A sprite draws it,
with the add-on's renderer,
GAMEPALETTE.checkerboardTileRenderer, so the map can be
moved, turned, and scaled like any sprite, and only the tiles on the
canvas are drawn, however large the map is. The renderer puts the
tiles together into one picture first, and draws that, so the tiles
meet without seams wherever the map is, even part-way between
pixels as it scrolls smoothly. The
Checkerboard map demo
has a walker to steer round an animated map, kept off the rocks
and water by a passable property in its tileset
data.
See
checkerboardmap.html
for the full description of the add-on.
Anything you find yourself writing for more than one game, such as a way of moving sprites, a kind of collision test, or a special renderer, can become an add-on. An add-on is an ordinary JavaScript file that does three things:
GAMEPALETTE.addAddOn,
giving its name and any functions the engine should call for it
(its hooks);GAMEPALETTE.Here is a complete add-on, mover.js. It adds a
class, GAMEPALETTE.Mover, which gives a sprite a
velocity; after each step of the game's logic, the engine has the
add-on move every mover's sprite by its velocity, so the game
doesn't have to move each one itself.
"use strict";
// Mover: an add-on that moves sprites at a steady velocity every logic
// step, so the game doesn't have to move each one itself
if(typeof GAMEPALETTE == "undefined")
{
throw new Error("mover.js needs gamepalette.js; load that first");
}
GAMEPALETTE.addAddOn({
name: "Mover",
version: "1.0",
// After each step of the game's logic, move every mover's sprite
afterLogicStep(engine)
{
for(let mover of GAMEPALETTE._moverList(engine))
{
if(mover.sprite.isActive == true)
{
mover.sprite.x += mover.velocityX;
mover.sprite.y += mover.velocityY;
}
}
}
});
GAMEPALETTE.Mover = class
{
constructor(engine, sprite, velocityX = 0, velocityY = 0)
{
if(engine instanceof GAMEPALETTE.Engine == false)
{
throw new TypeError("Engine is not an instance of " +
"GAMEPALETTE.Engine");
}
if(sprite instanceof GAMEPALETTE.Sprite == false)
{
throw new TypeError("Sprite is not an instance of " +
"GAMEPALETTE.Sprite");
}
this._engine = engine;
this._sprite = sprite;
this.velocityX = velocityX;
this.velocityY = velocityY;
GAMEPALETTE._moverList(engine).push(this);
};
get sprite()
{
return this._sprite;
};
get velocityX()
{
return this._velocityX;
};
set velocityX(velocityX)
{
if(Number.isFinite(velocityX) == false)
{
throw new TypeError("velocityX must be a finite number");
}
this._velocityX = velocityX;
};
get velocityY()
{
return this._velocityY;
};
set velocityY(velocityY)
{
if(Number.isFinite(velocityY) == false)
{
throw new TypeError("velocityY must be a finite number");
}
this._velocityY = velocityY;
};
deleteSelf()
{
let movers = GAMEPALETTE._moverList(this._engine);
let index = movers.indexOf(this);
if(index != -1)
{
movers.splice(index, 1);
}
};
};
// The engine's list of movers, kept in the add-on's data so that saveState
// saves it and loadState puts it back
GAMEPALETTE._moverList = (engine) =>
{
let data = engine.getAddOnData("Mover");
if(data.movers === undefined)
{
data.movers = [];
}
return data.movers;
};
A game uses it like this, after loading mover.js
after gamepalette.js:
// In "setupGame": the asteroid drifts 2 pixels right and 1 down
// each step, with no more code in the main loop
s.asteroid = new GAMEPALETTE.Sprite(s.engine, s.asteroidImage, 0, 0);
s.asteroid.isActive = true;
s.asteroidMover = new GAMEPALETTE.Mover(s.engine, s.asteroid, 2, 1);
The Add-ons demo uses this add-on, along with another that draws a debugging overlay. The rest of this chapter goes through the parts of an add-on.
An add-on file starts by checking that GAMEPALETTE
exists, so that loading the files in the wrong order gives a clear
message rather than a puzzling error further on. Then it calls
GAMEPALETTE.addAddOn,
once, with an object describing the add-on:
name: the add-on's name, such as
"Mover". It must be different from every other
add-on's.version (optional): its version, as a string
such as "1.0".requires (optional): an array of the names of
other add-ons it needs. If one of them hasn't been loaded,
addAddOn throws an error saying which.addAddOn checks the description carefully: a
misspelled hook name, such as afterLogicSteps, throws a
TypeError straight away, rather than leaving a hook
that silently never runs. Call it before anything else in the
file, so that nothing is added to GAMEPALETTE if it
fails (because an add-on of the same name is already loaded, for
instance).
Hooks are the add-on's functions that the engine calls at set moments, so that the add-on can take part in running the game without the game having to call it. Each is given the engine, and each is optional; include only those the add-on needs. The engine calls the hooks of every add-on that has them, in the order the add-ons were added.
engineCreated(engine): called when an engine is
created, at the end of its constructor, to set up anything the
add-on needs for each engine; for example, to name the add-on's
functions for saving with the engine's
addSaveName.
If engines already exist when the add-on is added, it's called for
each of them then.beforeLogicStep(engine): called at every logic
step, just before the game's logic function.afterLogicStep(engine): called at every logic
step, just after the game's logic function, and before the engine
moves the auto-camera,
so the camera follows a sprite the add-on moves. This is the
usual hook for an add-on that moves things, like the Mover.beforeDraw(engine): called each time a frame is
drawn, before anything else is drawn, even the
background
function. Draw on the canvas with
engine.cc.afterDraw(engine): called each time a frame is
drawn, after everything else, even the
foreground
function, so whatever it draws is on top of everything: for
example, a display of debugging information.afterLoadState(engine): called after the engine's
loadState has
put back a saved game, for an add-on that needs to bring anything
of its own up to date.The step hooks run for every logic step, at the rate set by
desiredFPS,
and only while the engine is running, just like logic functions.
The two drawing hooks are given the canvas in canvas coordinates,
with (0, 0) at its top-left corner, as the background and
foreground functions are, and the canvas's settings are saved
before each and restored after it, so a drawing hook can change
them freely without affecting the rest of the frame. An error
thrown in a hook stops that frame, as an error in a logic function
does, and shows in the browser's console.
Everything in Game Palette whose name begins with an underscore,
such as sprite._x or engine._sprites, is
the library's own business: it may change or vanish in any new
version. An add-on should use only the public properties and
functions described in the Reference
chapter, as a game does, so that it keeps working as the library
changes. (The two add-ons that come with Game Palette work this
way too.) The public interface also checks what you give it, so
mistakes, such as a misspelled name, show up as errors at once
instead of as odd behavior later. An add-on's own classes may of
course have underscore names of their own, for the add-on's
private use.
Besides everything a game uses, some parts of the interface are there mainly for add-ons and renderers:
engine.activeSprites:
the active sprites, in the order they are drawn, for an add-on that
works with every sprite in the game, such as a collision
test;engine.animationTime:
the clock that sprite animations follow, for an add-on that
animates things of its own in step with them, as the
CheckerboardMap's tiles do;engine.visibleArea():
the part of the game that is on the canvas, in the canvas
context's current coordinates, so a renderer can draw only what
can be seen;image.drawFrame(),
image.img, and
image.isImageLoaded:
for drawing an image's frames, or any part of its picture;engine.getAddOnData():
a place to keep the add-on's own information for each engine,
which is saved with the game (see below).A renderer that an add-on provides is written just as described in Writing a renderer.
An add-on adds its classes and functions to
GAMEPALETTE, as GAMEPALETTE.Mover, so that
games use them just like the library's own. Choose names that
won't clash with the library's or another add-on's: a class named
after the add-on, as here, is a good choice. Helper functions that
games shouldn't use start with an underscore and the add-on's name,
like GAMEPALETTE._moverList. Follow the library's
conventions, too, so that the add-on feels like part of it:
camelCase names, classes that take the engine as their first
argument, properties with getters and setters that check their
values, and a TypeError for a value of the wrong type
or a RangeError for one out of range.
An add-on's objects can be saved with the engine's
saveState like
any other, as long as the add-on is written with saving in mind:
GAMEPALETTE already
has a name for saving, so the add-on's objects are saved with all
their fields, and its renderers by name. Anything else the
add-on's objects refer to must be something
saveState can save; a function or class that isn't
on GAMEPALETTE needs a name from
addSaveName,
which the add-on can give it in its engineCreated
hook.engine.getAddOnData
is for. It gives each add-on a plain object for each engine, in
which the add-on can keep anything that can be saved;
saveState saves it, and loadState
replaces it with the saved one. Since it's replaced, get it from
the engine each time it's needed, as
GAMEPALETTE._moverList does, rather than keeping it.
And since a game saved before the add-on was in use has no data
for it, the add-on should cope with finding it empty, as
_moverList does by making the list when it's
missing.#private fields can't be saved; use fields starting
with an underscore instead.The Mover class can be saved without any more work:
the movers, their sprites, and the list of movers all come back with
a loaded game, and go on moving.
This reference section contains full descriptions for all the
public functions and properties exposed in the classes included
with Game Palette's core library, gamepalette.js,
including the functions for writing add-ons (see
Add-Ons). The add-ons that come with Game
Palette are described in their own files:
linkedsprite.html and
checkerboardmap.html.
To begin, you may jump here to the class you're interested in.
The Engine is the fundamental object that orchestrates and maintains control of your game. In most cases, you will instansiate one instance of this class and will pass a reference to it to the other assets and other objects that are to be made a part of your game.
new GAMEPALETTE.Engine(canvasId)
Creates the engine that will run your game on the canvas whose
id is canvasId. The canvas must already
be on the page when this runs, so put your game's script after the
canvas tag, as all the demos do. If canvasId isn't a
string, or no element has that id, or the element
isn't a canvas, the constructor throws a TypeError
and no engine is made. (See
canvasId.)
A new engine is stopped
(isRunning
is false) and in
logicMode
"init", which does nothing until you add your own "init" logic
function. It runs at 30 steps a second
(desiredFPS),
with the camera at (0, 0), unturned, perspective view and the auto
camera off, a background that fills the canvas with black, no
foreground, and
smoothing
on. Every property starts at the default listed for it below.
The engine also creates the state object that it passes to
every logic function. It starts with two properties,
engine and its short form e, both
referring to the engine, so a logic function can reach the engine
as s.engine or s.e. Keeping your game's
variables on the state object is what lets
saveState
save them.
Finally, the engine starts listening to the keyboard (for
GAMEPALETTE.KeyInput) and to the
window gaining and losing focus (for
pauseOnWindowBlur).
It listens to the whole page and keeps listening for as long as the
page is open, so make one engine per page. Sound isn't set up
until the first GAMEPALETTE.Sound is created.
A game's script follows the same outline every time: make the engine, add the logic functions, and start it. The Simple sprite control demo is a complete example.
let engine = new GAMEPALETTE.Engine("gameCanvas");
engine.addLogicFunction("init", (s) =>
{
// Create images and sounds, then move on
s.engine.logicMode = "mainLoop";
});
engine.addLogicFunction("mainLoop", (s) =>
{
// Run one step of the game
});
engine.isRunning = true;
The properties fall into a few groups: running the game
(isRunning through logicMode), the canvas
(canvasId through smoothing), drawing
around the sprites (backgroundFunction
and foregroundFunction), the camera
(cameraX through autoCameraBottomLimit),
sound (masterVolume and soundCategories),
and loading (loadProgress through
loadErrors). Setting a property to a value of the
wrong type throws a TypeError, and to a value out of
range a RangeError; in either case the property keeps
its old value.
Whether the engine is running. While it runs, the engine calls
the current logic function
(see logicMode)
desiredFPS
times a second, animates the sprites, moves the auto camera, and
redraws the canvas. An engine is created stopped, so that you can
add your logic functions first; set isRunning
to true, usually as the last line of your script, to
start the game. Any value is accepted and treated as true or
false.
Setting it to false pauses the whole game: no logic
runs, nothing is redrawn (the last frame stays on the canvas), and
all sound stops exactly where it is, fades included. Setting it
back to true carries on from the same point, and sounds
resume where they left off (except sounds the game has paused
itself; see the Sound class). Time spent stopped isn't made up
afterwards. Key presses are still noticed while the engine is
stopped, so a key's keyDownFunction can unpause the
game.
Sound can only play while the engine runs. A sound started while the engine is stopped begins when the engine starts.
Browsers stop drawing web pages in tabs that aren't showing, so
a running game also freezes while its tab is hidden, although
isRunning stays true and sounds keep
playing. To pause sound as well, use
pauseOnWindowBlur.
When true, the engine stops itself
(sets isRunning
to false) whenever the game's window loses focus: the
player switches to another tab or window, or clicks outside the
browser. This pauses the game and its sounds. When the window
gets focus back, the engine starts again.
It only restarts a game that it paused itself. If your game
sets isRunning while the window is out of focus (for
instance to show a pause screen), that choice stands and the engine
won't restart on focus.
Whatever this is set to, every key is treated as released when the window loses focus, so that a key held down at that moment doesn't stay "pressed".
How many times a second the engine runs your logic function.
Each call is one step of the game, so this sets the speed of the
game itself: a sprite your logic function moves 4 pixels per step
moves 120 pixels a second at 30 FPS and 240 at 60. A change takes
effect straight away. Sprite animations are not tied to it: they
play at their own images'
frameRate, by
the clock.
The engine keeps to this rate by the clock, whatever the screen's refresh rate. It redraws the canvas once after each step, or after the last of several steps when the screen refreshes less often than the game steps (a 60 FPS game on a 30 Hz screen runs two steps per redraw). It never redraws when no step has run, since nothing will have changed.
If the game can't keep up, because the logic or the drawing takes
too long, the engine runs up to 4 steps before each redraw to catch
up. Beyond that the game slows down rather than jumping ahead. The
engine also doesn't try to catch up after a pause of more than a
quarter of a second (a hidden tab, or a debugger stopping the
script); it simply carries on. To see how fast the game is
actually running,
see actualLogicFPS
and
actualVisualFPS.
See it in use in the Timing demo.
How many times in the last second the logic function actually
ran (actualLogicFPS) and the canvas was actually
redrawn (actualVisualFPS). They are measured over
each half second while the engine runs, so they change twice a
second and are always even numbers. Until the first measurement
they read 30, and while the engine is stopped they keep their last
values.
When all is well, actualLogicFPS is the same
as desiredFPS
(give or take 2, as steps fall on either side of a
half-second boundary). If it is lower, the game can't keep up and
is running slow. actualVisualFPS is never higher
than actualLogicFPS or the screen's refresh rate; when
it is lower than actualLogicFPS, the engine is running
more than one step per redraw. Showing these in
a
foregroundFunction
is a handy way to check a game's speed while you work on it.
See it in use in the Timing demo.
The name of the logic function the engine calls on each step.
Logic functions are added, each under a name,
with
addLogicFunction.
Setting logicMode to a name that hasn't been added
throws a RangeError, so add a logic function before
switching to it.
The engine starts in "init", and provides an "init" that does
nothing in case you don't add your own. A game is a series of
modes, each switching to the next when it's done. The demos with
pictures all follow the same pattern: "init" creates the images and sounds
and
switches to "loadScreen"; "loadScreen" waits
for loadProgress
to reach 100 and switches to "setupGame"; "setupGame" creates the
sprites and key inputs and switches to "mainLoop"; and "mainLoop"
runs the game until, say, it switches to "gameOver". A change
made during a step takes effect from the next step, so the logic
function that sets it always finishes its current call. See
the Simple sprite control
demo for the pattern at its simplest.
canvasId passed to the
constructor
The id of the HTML canvas element the engine draws
on. It is first set by the constructor, and usually never changes.
You may set it to the id of another canvas, and the
engine draws on that one from the next frame; cc,
canvasWidth, and canvasHeight then refer
to the new canvas.
Setting it throws a TypeError if the value isn't a
string, if no element on the page has that id, or if
the element isn't a canvas. The engine then keeps drawing on the
canvas it had.
canvasId
The canvas's 2D drawing context, for drawing with the browser's
own canvas functions (fillRect, drawImage,
fillText, and so on). The engine passes it to
renderers, to
the
backgroundFunction,
and to
the
foregroundFunction,
which is where your drawing belongs. Anything drawn from a logic
function is painted over when the frame is drawn.
The engine resets the context's transform at the start of each
frame, and sets the transform and globalAlpha while it
draws sprites, putting them back afterwards. Other settings you make
(fillStyle,
font, and the like) stay set until something changes
them, so set what you need each time you draw.
width and
height attributes
The size of the canvas in drawing pixels: the
width and height attributes of the canvas
tag. This is the space your game has to draw in, with (0, 0) at
the top left. It isn't necessarily the size the canvas appears on
the screen: CSS can stretch or shrink the canvas, and the browser
scales the drawing to fit. (See chapter
2, Skeleton, for more about this.)
They are read from the canvas each time, so they are always
current. To resize the canvas, set the canvas element's own
width and height (for example
engine.cc.canvas.width = 800); the engine picks up the
new size on the next frame and keeps the camera point at the
center. Resizing a canvas resets its drawing context's settings;
the engine puts its own
(smoothing and
the transform) back before each frame, but any others you've made
must be made again.
Whether images are smoothed when they are drawn scaled or
rotated. With true, the browser blends neighboring
pixels, which looks best for photographs and painted art.
With false, each image pixel becomes a sharp-edged
block, which keeps pixel art crisp when it's zoomed in. It is the
canvas context's imageSmoothingEnabled setting, and
setting anything other than a boolean throws
a TypeError.
The engine remembers the setting and applies it to the canvas
before drawing each frame, so it stays in effect when the canvas
is resized (which would otherwise turn it back on) and carries
over when canvasId
changes to another canvas.
See it in use in the Pixel art demo.
A function that draws the backdrop of each frame, before any sprites. It is called as
backgroundFunction(cc, cameraRotation)
with the canvas context and the
current
cameraRotation.
It draws in canvas coordinates: (0, 0) is the top-left corner of
the canvas, and the camera doesn't move it. The engine doesn't
clear the canvas between frames, so the background function must
cover the whole canvas, or the last frame shows through. For the
same reason, setting it to null leaves trails behind
anything that moves, which is only occasionally what you want.
The cameraRotation argument lets a backdrop turn
with the camera. The Parallax demo
fills the canvas with a sky gradient and then draws stars rotated
about the canvas center by -cameraRotation. If your
function changes the context's transform, put it back
(with cc.save() and cc.restore(), as the
demo does), or the sprites drawn after it will be moved too. (The
engine resets the transform at the start of each frame, so a
transform left behind lasts only for the rest of that frame.)
Setting anything other than a function
or null throws a TypeError.
A function that draws over each frame, after all the sprites:
the place for a score, lives, messages, or a pause screen. It is
called the same way as
the
backgroundFunction,
as foregroundFunction(cc, cameraRotation), and also
draws in canvas coordinates, so whatever it draws stays put as the
camera moves. null draws nothing. The
Parallax demo uses one to show the
camera settings in the top-left corner.
startForegroundLoadIndicator
works by setting this property to a function that draws a loading
bar, which sets the property back to null once
loading is complete. Set your own foreground function after
loading, or it will be replaced.
Where the camera points: the game-world point
(cameraX, cameraY) is drawn at the center
of the canvas. With both at 0, a sprite at (0, 0) appears in the
middle of the canvas. Moving the camera right (increasing
cameraX) makes everything appear to move left. The
background and foreground functions are not affected. Turn
to worldToCanvas
and canvasToWorld
to convert between game and canvas points.
While
the auto camera is
following a sprite, it sets these on every step, so any value you
set is soon overridden. The Fill
renderers demo moves the camera with the I, J, K, and L keys,
and the Checkerboard map
demo sets cameraX and cameraY to
start the view at the corner of its map, before the auto camera
takes over.
The camera's depth. It only has an effect
when
perspectiveView
is on, when sprites at z = cameraZ are drawn at their
normal size. Increasing it moves the camera forward, in among the
sprites: everything in front grows, and sprites it passes stop
being drawn. The Parallax demo
moves the camera in and out with the I and K keys.
How far the camera is turned, in radians (a full turn is
2 * Math.PI), about the point it points at.
Increasing it turns the camera clockwise, so the game world
appears to turn counterclockwise around the center of the canvas.
The value isn't wrapped to one turn. It doesn't rotate the
background or foreground functions, but it is passed to them so
they can follow it. The auto camera doesn't change it. Try it in
the Fill renderers demo (U
and O keys) or the Parallax
demo.
When perspectiveView is false, a
sprite's z only sets the order sprites are drawn in: larger z is
farther away, so it is drawn first, behind the rest.
When it is true, the engine also draws each sprite
as seen by a camera looking down the z axis. The plane at
z = cameraZ is
drawn at its normal size, and a sprite at depth z is drawn at
focalLength / (z - cameraZ + focalLength)
times its size, centered on the camera. Farther sprites are
smaller and scroll by more slowly as the camera moves, giving
parallax; nearer ones (z less than cameraZ) are larger
and move faster. Increasing cameraZ trucks the camera
in among the sprites. Sprites at or behind the camera, or closer
to it than 1/100 of
the focalLength,
are not drawn.
perspectiveScale
gives the scale for any depth. Any value is accepted and treated
as true or false. The Parallax
demo shows all of this.
How far the camera is behind the plane z = cameraZ
when
perspectiveView
is on. A sprite one focal length farther away is drawn at half
size. A shorter focal length gives a deeper view with stronger
parallax; a longer one, a flatter view. It has no effect
when perspectiveView is off. Setting a value that
isn't a finite number greater than 0 throws
a RangeError. In
the Parallax demo, the J and L
keys change it.
The sprite the auto camera follows. When this is set to a
sprite, the engine moves the camera after each step's logic
function so the sprite stays in the center of the canvas (or near
it; see the other auto-camera properties below). It
sets cameraX
and cameraY to
do this, so set them yourself only when the auto camera is off.
Set it to null to turn the auto camera off; the camera
then stays where it is.
It can also be set to an array of sprites, and the camera then
follows the average of their positions, keeping a group of players
in view together. The engine keeps its own copy of the array, so
changing your array afterwards has no effect; set the property
again instead. Reading it always gives an array (or
null), even after setting a single sprite. A sprite
that is turned off (its isActive set
to false) is dropped from the list; once none are
left, the camera stops moving.
The way the camera follows is set
by
autoCameraLooseness,
autoCameraCenterOffsetX,
autoCameraCenterOffsetY,
and the four limits,
autoCameraLeftLimit,
autoCameraRightLimit,
autoCameraTopLimit,
and
autoCameraBottomLimit.
The Parallax demo follows its UFO
with a loose camera kept within limits. Setting anything other
than a sprite, an array of sprites, or null throws
a TypeError.
See it in use in the Camera demo.
How lazily the auto camera follows its sprite. On each step the
camera moves 1 / (autoCameraLooseness + 1) of the way
to where it's aiming. At 0 it locks onto the sprite exactly. At 1
it moves half the remaining distance each step, at 3 a quarter,
and so on, so it lags behind a moving sprite and eases to a stop
when the sprite stops. A little looseness makes a camera feel
smooth; a lot makes it drift. The Parallax
demo uses 8. The value needn't be a whole number. A negative
value throws a RangeError.
Where on the canvas the auto camera keeps its sprite, as an
offset in game pixels from the center. The camera aims at the
sprite's position minus these offsets, so with
autoCameraCenterOffsetX set to 100 the sprite sits
100 pixels right of the center; with -100, 100 pixels left of it,
which shows more of what's ahead of a player running right.
Likewise, a positive autoCameraCenterOffsetY puts the
sprite below the center. (The offsets are in the game world, so
with the camera rotated, or the sprite away from z
= cameraZ in perspective, they appear turned or
scaled with it.)
The range of game points the auto camera may aim at, to keep the
view from wandering past the edges of the game world. The auto
camera keeps
cameraX between
the left and right limits
and cameraY
between the top and bottom ones (top is the smaller y).
null means no limit on that side. Keep each lower
limit no greater than its upper limit.
The limits apply to the camera point, the center of the view,
not to the edges of the canvas. To stop the left edge of the view
at a world edge at x = 0, set autoCameraLeftLimit to
half the canvas width: engine.canvasWidth / 2. For a
rotated camera, or with perspective on, allow more room; the
Parallax demo works out its limits
from its scenery. The limits only restrict the auto camera;
setting cameraX and cameraY yourself
isn't limited.
The volume of all the game's sound together, from 0 (silent)
to 1 (full). Every sound's own volume and its category's volume
are scaled by it, so this is the natural setting for a player's
volume control or a mute button. Values outside 0 to 1 are moved
to the nearer end rather than refused; a value that isn't a finite
number throws a TypeError.
To change it gradually,
use
fadeMasterVolume.
Reading masterVolume during a fade gives the volume at
that moment, and setting it cancels the fade. The
Sound demo has a master volume slider
and fade controls.
saveState
doesn't save it, treating it as the player's setting rather than
part of the game.
{}
The sound categories in use, as an object with one property per
category: the category's name, holding an array of the
GAMEPALETTE.Sound objects in it. A category exists once a sound is
given it (with the Sound's category) and disappears
when its last sound leaves it. Categories let you set the volume of
a group of sounds, such as "music" or "effects", together:
see
setCategoryVolume,
fadeCategoryVolume,
and
getCategoryVolume.
To go through the categories, use a for...in loop,
as the Sound demo does to build a
volume control for each:
for(let category in engine.soundCategories) {
console.log(category, engine.getCategoryVolume(category));
}
This is the engine's own record, not a copy, so look but don't change it. Change a sound's category through the sound instead.
How far the game's images and sounds have got with loading, as a percentage. Each GAMEPALETTE.Image and each GAMEPALETTE.Sound alternate starts loading as soon as it is created, and counts as done when it has loaded or failed to load. With nothing to load, the value is 100. It isn't a whole number in general.
A loading screen waits for it to reach 100 before going on: this is the "loadScreen" logic function in the demos, for example the Simple sprite control demo:
engine.addLogicFunction("loadScreen", (s) =>
{
if(s.engine.loadProgress == 100) s.engine.logicMode = "setupGame";
});
Creating more images or sounds later brings the value down again
until they have loaded. To measure a later batch on its own, from
0, call
resetLoadProgress
first. Because failures count as done, check
loadErrors to
find out whether everything arrived.
startForegroundLoadIndicator
draws a bar showing this value.
true when every image and sound created so far has
finished loading (or failed to load; see
loadErrors),
and false while any are still loading. It is the same
as loadProgress == 100, and is true when
nothing has been created yet.
[]
The URLs of the images and sounds that failed to load, in the order they failed: a missing file, a misspelled name, or a file the browser can't decode. For a sound offered in several formats none of which this browser can play, the entry lists them all, separated by commas. Each failure is also reported in the browser's console.
Failed files still count toward
loadProgress,
so a loading screen doesn't wait for them forever. Check this
array when loading is done to catch them, for example to show a
message instead of starting a game with missing pictures. Each
read gives a new copy of the array.
[]
The sprites that are active (see the Sprite's
isActive), in
the order they are drawn: farthest first, by
z, and among sprites
with the same z, those activated earlier first. Use it
to do something with every sprite in the game, such as testing
which ones overlap a point, or counting the enemies left; it's
mainly for add-ons (see Add-Ons). Each read
gives a new copy of the array, so it's safe to turn sprites on or
off while going through it; the copy doesn't change, so read it
again to see the change.
See it in use in the Add-ons demo.
The time on the clock that sprite animations follow, in seconds:
real time, counted only while the engine is
running, and moved on just
before each frame is drawn. Unlike counting logic steps, it keeps
real time even when the game slows down, which is how animations
keep to their frameRate.
Use it to animate something of your own in step with the sprites,
in a renderer or a drawing function; the CheckerboardMap add-on's
animated tiles use it. For example, the frame of an 8-frame,
12-frames-a-second animation to show now is
Math.floor(engine.animationTime * 12) % 8
It is saved by
saveState, so
animations carry on where they were after a game is loaded.
Adds a logic function to the engine under the name
logicName. While
logicMode is
that name and the engine is running, the engine calls the function
once per step,
desiredFPS
times a second, with the state object as its only argument:
logicFunction(state)
The state object is the same object on every call (see
the constructor), so
whatever one call stores on it, the next finds there, whichever
logic function makes the call. Most games name the parameter
s. The function's return value is ignored. After it
returns, the engine moves the
auto camera. Once
all the steps due have run, the engine moves the sprites'
animations on by the time that has passed (see
frameRate) and
draws the frame.
A logic function can be added at any time, even while the game
runs. Adding one under a name already in use replaces the old
function, which is how your own "init" replaces the engine's
do-nothing one. There is no way to remove a logic function, but
an unused one costs nothing. A logicName that isn't a
string, or a logicFunction that isn't a function,
throws a TypeError.
Returns the game in progress as a string, ready to keep (for
example in localStorage) and later hand
to loadState.
It holds:
null, undefined,
arrays, plain objects, Maps, Sets,
Dates, BigInts, sprites, linked sprites, checkerboard
maps, and instances of the game's own classes once they are named
with addSaveName.
Objects referred to from more than one place stay shared, and
objects may refer to each other in a circle;getAddOnData).Images, sounds, and key inputs are not copied into the save.
The save only records which ones they are, and loadState
finds the game's own again.
A function is saved by name. The library's own functions, such
as GAMEPALETTE.tileFillRenderer, already have names;
any other function the state refers to (a custom renderer, say) must
be named with addSaveName. saveState
throws a TypeError naming anything it can't save, such
as an unnamed function, an instance of an unnamed class, or a
canvas element, for example:
Can't save state.f: it's a function without a name for saving
(see engine.addSaveName)
Not saved: the engine's settings that don't change during play
(desiredFPS,
smoothing,
the background
and foreground
functions, the logic functions themselves), the
master and
category volumes
(usually the player's own settings), sounds partway through playing
(other than looping ones, which restart), fades in progress, and
which keys are held down. JavaScript #private class
fields can't be read from outside a class, so they aren't saved
either; use ordinary fields for anything that must be. The
Linked sprites demo saves
with the 1 key and loads with 2.
See it in use in the Save and load demo.
Puts back a game saved by
saveState;
savedState is the string it returned. The state
object stays the same object (so code holding on to it keeps
working), but its contents are replaced with the saved ones. Sprites
and other objects are made anew. Any sprite that was active and
isn't in the save is turned off. All sounds stop, and any looping
sounds that were playing when the game was saved start again.
Each add-on's data is replaced with the saved data, and then each
add-on's afterLoadState hook is called (see
Hooks).
Each image, sound, and key input in the save is matched to the
one the game has already made with the same URL and frame layout,
the same sound URLs, or the same keys, so they keep their
onComplete, triggers, and key functions. For the
match, create them the same way (for example in the "init" and
"setupGame" logic functions) before loading. If there's no match,
a new one is made from the saved details, without any of those
functions.
Before changing anything, loadState checks that the
save is whole and fits the game. If it doesn't (it was damaged,
it uses a function or class this game hasn't named with
addSaveName,
or it was in a logic mode this game doesn't have), it throws an
error explaining why, and the game carries on unchanged. Load from
a key function, a button, or a logic function; the new state is in
place for the next logic step. Saving and loading in the
Linked sprites demo look like
this:
s.keyLoad.keyDownFunction = () =>
{
try {
let saved = localStorage.getItem("myGameSave");
if(saved !== null) {
engine.loadState(saved);
}
} catch(error) {
// Show error.message to the player
}
};
Gives a function or class a name, so that
saveState
can save references to it, and instances of it if it's a class.
Use the same names every time the game runs, and name things before
calling loadState.
A function or class can have only one name: giving it a second
throws an Error. Giving a name to a different function
replaces the old one. A name that isn't a non-empty
string, or a functionOrClass that isn't a function or
class, throws a TypeError, and names starting with
GAMEPALETTE. are kept for the library
(a RangeError). When an instance of a named class is
loaded, its fields are filled in without calling its
constructor.
class Enemy { ... }
engine.addSaveName("Enemy", Enemy);
engine.addSaveName("glowRenderer", glowRenderer);
See it in use in the Save and load demo.
Returns the scale at which things at depth z are
drawn. When
perspectiveView
is off, that is always 1. When it's on, it is
focalLength / (z - cameraZ + focalLength)
(see focalLength
and cameraZ), or
0 for depths that aren't drawn: at or behind the camera, or closer
to it than 1/100 of the focal length. The engine uses it to size
each sprite, and it's useful for anything you draw yourself at a
depth, or for making a far-off sprite larger to make up for the
distance. The Parallax demo shows
the UFO's scale on screen with it, and scales its far-off moon up
by the inverse of this value so it still looks large.
A z that isn't a finite number throws
a TypeError.
Returns where the game point (x, y)
at depth z appears on the canvas, as an object
{x, y} in canvas pixels with (0, 0) at the top left.
It takes into account the camera's
position and
rotation and, when
perspectiveView
is on, the depth (see
perspectiveScale).
It returns null if that depth isn't drawn. Use it to
draw something in the
foregroundFunction
over a sprite, such as a name tag or health bar, or to find out
whether a sprite is on screen. An x, y,
or z that isn't a finite number throws
a TypeError.
let point = s.engine.worldToCanvas(s.player.x, s.player.y, s.player.z);
if(point !== null) {
cc.fillText("Player 1", point.x, point.y - 40);
}
The reverse of
worldToCanvas:
returns the game point at depth z that appears at
canvas point (x, y), as an object
{x, y}, or null if nothing at that depth
is drawn. With perspective on, a canvas point shows a different
game point at each depth, so give the depth you mean. An
x, y, or z that isn't a
finite number throws a TypeError.
Its main use is turning a mouse or touch position into game
coordinates. Mouse positions are in CSS pixels, so if the canvas
is shown at a different size from its width and
height (see
canvasWidth),
scale them first:
let canvas = engine.cc.canvas;
canvas.addEventListener("click", (event) =>
{
let x = event.offsetX * canvas.width / canvas.clientWidth;
let y = event.offsetY * canvas.height / canvas.clientHeight;
let point = engine.canvasToWorld(x, y);
// point.x, point.y is where the player clicked in the game
});
See it in use in the Mouse and touch demo.
Changes
masterVolume
gradually, in a straight line from its current value
to targetVolume over duration seconds:
for example, engine.fadeMasterVolume(0, 2) fades all
sound out over two seconds. A targetVolume outside 0
to 1 is moved to the nearer end. A new fade replaces one already
under way, starting from wherever that one had got to, and setting
masterVolume cancels it. Fades run on the sound clock,
which stops while the engine is stopped, so a fade pauses with the
game. A targetVolume that isn't a finite number
throws a TypeError, and a duration that
isn't a finite number greater than 0, a RangeError.
Try it in the Sound demo.
Sets the volume of the sound category named
category, from 0 (silent) to 1 (full); values outside
that range are moved to the nearer end. Each sound's volume is
scaled by its category's volume and then by
masterVolume,
so this turns a whole group of sounds up or down together, such as
all the music or all the sound effects. Setting the volume cancels
any fade of that category.
A category exists while at least one sound belongs to it (see
soundCategories).
Naming one that doesn't exist throws a TypeError, and
so does a newVolume that isn't a finite number. When
a category's last sound leaves it, the category and its volume are
forgotten; if a sound joins it again later, it starts at full
volume. The Sound demo has a volume
slider for each category.
Changes the volume of the sound category category
gradually, in a straight line from its current value
to targetVolume over duration seconds:
for example, engine.fadeCategoryVolume("music", 0.3, 1)
lowers the music over a second while a character speaks. It works
like
fadeMasterVolume:
the target is kept within 0 to 1, a new fade replaces one under
way,
setCategoryVolume
cancels it, and it pauses while the engine is stopped. A category
that doesn't exist, or a targetVolume that isn't a
finite number, throws a TypeError, and
a duration that isn't a finite number greater than 0,
a RangeError.
Returns the current volume of the sound category
category, from 0 to 1. During a fade, it's the volume
at that moment. Naming a category that doesn't exist (see
soundCategories)
throws a TypeError.
Starts
loadProgress
counting afresh. Images and sounds that have finished loading are
no longer counted, and those still loading stay in the count, so
the value is then 0 if anything is still loading and 100 if
nothing is. Use it before creating a new batch of images and
sounds partway through a game, such as the next level's, so that a
loading screen measures just that batch from 0. It doesn't clear
loadErrors.
Shows a simple loading bar in the center of the canvas until
loading is done. It sets the
foregroundFunction
to one that draws a bar 400 pixels wide, outlined in
indicatorOutlineStyle and filled in
indicatorStyle in proportion to
loadProgress.
Both styles are canvas color strings, such as "red",
"#00ff00", or "rgb(0, 0, 255)"; anything
other than a string throws a TypeError. The first
frame drawn with loadProgress at 100 draws the full
bar and then sets the foregroundFunction back
to null, removing the bar.
Call it in your "init" logic function, after creating the images and sounds, and go on to set up the game once loading is done, as all the demos with pictures do (the Simple sprite control demo, for one). It replaces any foreground function you've set, and removes itself rather than restoring yours, so set your own foreground function after loading.
Returns the part of the canvas context's current coordinate
space that is shown on the canvas, as an object
{left, top, right, bottom}: the smallest rectangle, in
those coordinates, that covers the whole canvas. In a renderer,
where the coordinates are the sprite's own (see
Writing a renderer),
it says which part of the sprite's plane can be seen, so that a
renderer drawing something large, such as a map or a pattern, can
skip everything outside it. When the sprite or camera is turned,
the canvas covers a turned rectangle in those coordinates, and the
area returned is the upright rectangle around it, so it may include
a little that isn't on the canvas. It returns null
when the current transform squashes everything to nothing (a sprite
with a scale of 0), when there
is nothing to draw. This draws a grid line every 100 pixels across
whatever part of a sprite's plane is visible:
function gridRenderer(engine, sprite)
{
let area = engine.visibleArea();
if(area === null) return;
engine.cc.strokeStyle = "gray";
engine.cc.beginPath();
for(let x = Math.ceil(area.left / 100) * 100; x < area.right;
x += 100) {
engine.cc.moveTo(x, area.top);
engine.cc.lineTo(x, area.bottom);
}
engine.cc.stroke();
}
See it in use in the Custom renderers demo.
Returns the data object of the add-on named
addOnName for this engine: a plain object, empty to
begin with, in which an add-on keeps whatever it needs to remember
for each engine, such as a list of its objects. It's the same
object each time, until a game is loaded. The engine's
saveState saves
each add-on's data object and everything in it, and
loadState
replaces it with the saved one (or with an empty object, if the
save has none for the add-on), so get it from the engine each time
you need it rather than keeping it. An addOnName that
isn't a string throws a TypeError, and one that isn't
the name of an add-on that has been added (see
GAMEPALETTE.addAddOn),
a RangeError. See
Saving in the Add-Ons chapter for how
to use it.
An Image is a picture for sprites to show: a single picture, or
an animation made of several frames of the same size. It loads the
picture file from a URL and holds the details of how to show it:
the size of each frame, how many frames there are, how fast they
play, which point of the frame sits at the sprite's position, and
what happens when the animation reaches its end. An Image draws
nothing by itself; a
GAMEPALETTE.Sprite shows it, and any
number of sprites can share one Image, each at its own place in the
animation. Create your images in your "init" logic function, so
that a loading screen can wait for them (see
loadProgress).
new GAMEPALETTE.Image(engine, imageURL, width, height,
frameCount = 1, frameRate = 30,
handleOffsetX = 0, handleOffsetY = 0,
onComplete = 0)
Creates an image for engine (your
GAMEPALETTE.Engine) and starts
loading the picture file at imageURL. The other
arguments set the properties of the same names (the frame size is
set by width and height, which become
imageWidth and
imageHeight),
and are checked the same way: see each property for what it does
and what it accepts. If any argument isn't acceptable, the
constructor throws a TypeError or
RangeError, and so does an engine that
isn't a GAMEPALETTE.Engine.
The file loads in the background; the constructor doesn't wait
for it. Until it has loaded, sprites showing the image draw
nothing. The image counts toward the engine's
loadProgress
from the moment it's created, and if the file can't be loaded, its
URL is added to
loadErrors.
For an animation, the frames go side by side in a single row in
the picture file, left to right, each width by
height pixels, with no gaps. The file is then
frameCount * width pixels wide and
height pixels tall. For example, the UFO in the
Simple sprite control
demo is ufo.png, 2000 by 70 pixels, holding eight
frames of 250 by 70. Its image plays them at 30 frames a second,
with the handle in the middle of each frame:
s.ufoImage = new GAMEPALETTE.Image(s.engine, "ufo.png",
250, 70, 8, 30, 125, 35);
A single picture is just an animation of one frame, so the last five arguments can usually be left out, as in the Fill renderers demo:
s.starsImage = new GAMEPALETTE.Image(s.engine, "stars.png", 200, 200);
Setting a property to a value of the wrong type throws
a TypeError, and to a value out of range
a RangeError; in either case the property keeps its
old value. Changes take effect for every sprite using the image
from the next frame drawn.
imageURL passed to the
constructor
The URL of the picture file. A relative URL is relative to the
page the game is on, so "ufo.png" means a file in the
same folder as the page. Any picture format the browser can show
will do; PNG is the usual choice, since it keeps sharp edges and
can have transparent parts.
Setting it to a new URL loads the new file in place of the old
one, keeping all the other settings. While the new file loads,
isImageLoaded
is false and sprites showing the image draw nothing,
so it's best done during a loading screen. The new file counts
toward loadProgress
like a newly created image. If the old file was still loading, it
is dropped when it arrives. Anything other than a non-empty string
throws a TypeError.
imageURL
The browser's own image element holding the picture file, the
kind made by new Image() or an <img>
tag (not to be confused with GAMEPALETTE.Image). Use it to draw
the picture yourself with the canvas's drawImage, in a
renderer of your own or in a
background or
foreground
function. For example, this draws frame 3 of an image at the top
left of the canvas:
cc.drawImage(s.ufoImage.img,
3 * s.ufoImage.imageWidth, 0,
s.ufoImage.imageWidth, s.ufoImage.imageHeight,
0, 0, s.ufoImage.imageWidth, s.ufoImage.imageHeight);
Check
isImageLoaded
before drawing it. Setting
imageURL replaces
the element with a new one, so read img again
afterwards rather than keeping the old one.
true once the picture file has loaded and can be
drawn. It is false while the file is loading, again
while a new file loads after
imageURL is
changed, and for good if the file can't be loaded (its URL is then
in the engine's
loadErrors).
Sprites showing an image that isn't loaded simply draw nothing. To
wait for all of a game's images at once, use the engine's
loadProgress
or assetsLoaded
instead.
width and
height passed to the constructor
The size of one frame, in pixels. Frame n (counting from 0) is
the part of the picture file from x = n * imageWidth
to (n + 1) * imageWidth, and from the top down
to imageHeight. For a single picture, this is usually
the size of the whole file. Showing less than the whole file
shows just its top-left part; showing more leaves the rest
empty.
A size of 0 draws nothing with the usual renderers. That's
useful for an image that's only a picture file for something else
to cut up: the Checkerboard map
demo's tileset image is created with a size of 0 by 0, because
a GAMEPALETTE.CheckerboardMap sets its own tile size
and lays the tileset out in rows. A value that isn't a whole number
throws a TypeError, and a negative one,
a RangeError.
How many frames the animation has. 1 means a still picture.
Each sprite showing the image plays the frames in order at
frameRate, and
when it passes the last one, does what
onComplete
says. A sprite's place in the animation is its
frame, which can be from 0 up to (but not including)
frameCount.
When you lower frameCount, active sprites that were
past the new last frame are moved onto it. If
onComplete is a frame number, it must stay below the
new count, so lower onComplete first; otherwise
setting frameCount throws a RangeError.
A value that isn't a whole number throws
a TypeError, and one less than 1,
a RangeError.
How fast the animation plays, in frames per second. The engine
keeps to it by the clock: before drawing each frame, it moves every
active sprite showing the image on by frameRate times
the seconds that have passed since the last frame was drawn. So a
frameRate of 10 shows each frame for a tenth of a
second, whatever the screen's refresh rate or the game's
desiredFPS.
Fractions are fine.
When frames are drawn less often than the animation's frames
change (a fast animation, or a game that can't keep up), the
sprite skips the frames in between, so the animation still runs at
its proper speed. Skipped frames still count:
triggers on them fire, and
running past the end still does what
onComplete
says. Unlike the rest of the game, then, animations don't slow
down when the game falls behind. They do stop while the engine is
stopped and while the sprite isn't active, and carry on from the
same place afterwards.
For a single-frame image, the rate makes no difference to how it
looks, but it sets how often
onComplete
takes effect (each pass through the one frame lasts 1 /
frameRate seconds). A
GAMEPALETTE.CheckerboardMap also uses its tileset
image's frameRate for its tile animations, unless it
is given its own. A value that isn't a finite number throws
a TypeError, and one that is 0 or less,
a RangeError.
The image's handle: the point in each frame, in pixels from the
frame's top-left corner, that is placed at the sprite's position.
The sprite also turns and scales about this point. With the
default of (0, 0), the top-left corner of the picture sits at the
sprite's position and the sprite spins about that corner. Common
choices are the center of the frame
(imageWidth / 2, imageHeight / 2), for
things that spin or move freely, and the middle of the bottom edge,
for things that stand on the ground.
The demos show both. In the
Simple sprite control
demo, the UFO's handle is (125, 35), the center of its 250 by
70 frames, so it turns about its middle. In the
Parallax demo, the trees' handle
is (70, 260), the bottom center of their 140 by 260 frames, so a
tree's position is where its trunk meets the ground. In the
Linked sprites demo, each
part of the robot has its handle at the joint where it attaches,
such as (19, 0) for the left arm's shoulder. The handle may be a
fraction (the robot's wheels use 15.5) or outside the frame. A
value that isn't a finite number throws
a TypeError.
What a sprite does when its animation runs past the last frame. It can be one of three things:
frameCount - 1:
the animation goes back to that frame and plays on from there, so
the frames from it to the end repeat for ever. The default, 0,
repeats the whole animation. A higher number gives an animation
that plays its first part once and then repeats the rest, such as
a character who stands up and then breathes.onComplete then says what happens at its
end.onComplete(sprite). The function may do anything:
change the sprite's image (the sprite then starts that
image), turn the sprite off once a one-time effect has played, or
count the loops. It's called while the engine moves the
animations on, after the frame's logic steps and before it's
drawn.
// An explosion that plays once and then removes its sprite
s.boomImage = new GAMEPALETTE.Image(s.engine, "boom.png",
64, 64, 12, 24, 32, 32,
(sprite) => sprite.isActive = false);
The animation moves on in jumps, one per frame drawn, so a
sprite usually runs a little past the last frame before
onComplete takes effect. The extra is carried over
into what comes next, so the animation keeps an even speed; if it
is more than a whole loop, onComplete takes effect
again for each loop. To have an animation stop on its last frame, lead into
a
one-frame image of that last frame (its own
onComplete repeats that one frame). With a
single-frame image, a function is called every 1 /
frameRate
seconds.
The setting is shared by every sprite using the image. A frame
number that isn't a whole number throws a TypeError,
and one outside the image's frames, a RangeError; so
does anything else that isn't an Image or a function
(a TypeError). When the game is saved with
saveState,
images aren't copied into the save, so a function here doesn't need
a save name.
Draws frame number frame of the image on the
engine's canvas, at its own size, with its top-left corner at
(x, y) in the canvas context's current
coordinates. A fraction is rounded down, as a sprite's
frame is, and a
frame number outside the image is moved to the first or last frame.
Before the image has loaded (or if it failed to), it draws nothing,
so there's no need to check
isImageLoaded
first. A frame, x, or y
that isn't a finite number throws a TypeError.
It's the easy way to draw an image yourself: in a
foreground
function, to draw a picture that stays put on the screen, such
as a lives counter; or in a renderer of your own (see
Writing a
renderer), where (0, 0) is where the sprite's image belongs.
The
singleImageRenderer
is just sprite.image.drawFrame(sprite.frame). To draw
it scaled, turned, or faded, change the context's transform or
globalAlpha first; to draw part of a frame, use
img instead.
// In the foreground function: a heart for each life left
for(let life = 0; life < s.lives; life++) {
s.heartImage.drawFrame(0, 10 + (life * 20), 10);
}
The image's other functions manage its triggers. A trigger is a function the engine calls whenever a sprite's animation reaches a chosen frame of the image, to make something happen at a precise moment in the animation: a footstep sound on the frames where a foot lands, a shot fired on the frame where a gun recoils, a hit checked on the frame where a sword swings through. Triggers belong to the image, so they work for every sprite showing it, and tell you which sprite it was.
Adds a trigger: from now on, whenever the animation of a sprite
showing this image reaches frame number frame
(counting from 0), the engine calls the function
trigger as
trigger(sprite, frame)
with the sprite that reached the frame and the frame number.
Returns the trigger's number, a whole number that identifies it
for removeTrigger.
Numbers count up from 0 for each image and aren't reused. An image
may have any number of triggers, including several on one frame,
which fire in the order they were added.
// Footsteps on the two frames where a foot lands
s.walkImage = new GAMEPALETTE.Image(s.engine, "walk.png",
48, 64, 8, 12, 24, 64);
s.walkImage.addTrigger(1, (sprite) => s.stepSound.play());
s.walkImage.addTrigger(5, (sprite) => s.stepSound.play());
"Reaching" a frame means the animation moving on to it, as the
engine moves animations on before drawing each frame (see
frameRate).
In detail:
frame is that frame while the trigger runs.onComplete
frame it loops back to, or frame 0 of the image it leads into
(that image's triggers then fire). With an
onComplete function, the function is called first,
and frame 0's triggers fire afterwards if the sprite is still on
frame 0 of this image.image or frame by your
code.GAMEPALETTE.CheckerboardMap's tile animations don't
fire triggers.A trigger may do anything, including change the sprite. If it
turns the sprite off, or gives it a different image
or frame, that change stands: the rest of that move
is dropped, and the animation carries on from wherever the trigger
left the sprite the next time it moves. Triggers are called while
the engine moves the animations on, after the frame's logic steps
and before it's drawn.
A frame that isn't a whole number throws
a TypeError, and one that isn't one of the image's
frames (0 to frameCount
− 1), a RangeError. If frameCount
is later lowered below a trigger's frame, the trigger stays but
doesn't fire unless the frame comes back. A trigger
that isn't a function throws a TypeError. When the
game is saved with
saveState,
images aren't copied into the save, so triggers don't need save
names; the game's own image keeps its triggers when the save is
loaded.
See it in use in the Animation demo.
Returns the image's triggers, as an array in the order they were added, with one object for each:
{triggerNumber, frame, trigger}
where triggerNumber is the number
addTrigger
returned, frame the frame it fires on, and
trigger the function. The array and its objects are
copies, so changing them doesn't change the triggers; use
addTrigger and
removeTrigger
for that. With no triggers, it returns an empty array. For
example, this removes all of an image's triggers:
for(let trigger of s.walkImage.getTriggers()) {
s.walkImage.removeTrigger(trigger.triggerNumber);
}
Removes the trigger with the number triggerNumber,
as returned by
addTrigger,
so it no longer fires. It may be called from inside a trigger,
including the trigger being removed. A
triggerNumber that isn't a whole number throws
a TypeError, and one that isn't the number of one of
this image's triggers (perhaps already removed), a
RangeError.
A Sprite is one thing in the game world: a player, an enemy, a tree, a backdrop, a line of text. It has a position, a depth, a rotation, a size, and a transparency, and a renderer that draws it, usually showing a GAMEPALETTE.Image. A sprite is only drawn (and its animation only plays) while it is active. Your logic functions move sprites about by changing their properties, and the engine draws all the active ones each frame, the farthest first, as the camera sees them.
new GAMEPALETTE.Sprite(engine, image, x, y, z = 0,
renderer = GAMEPALETTE.singleImageRenderer,
rendererParameter = null, rotation = 0,
alpha = 1, randomizeStartFrame = false)
Creates a sprite for engine (your
GAMEPALETTE.Engine) showing
image, a GAMEPALETTE.Image or null, at
the game point (x, y) and depth
z. The other arguments set the properties of the same
names, and are checked the same way: see each property for what it
does and what it accepts. An unacceptable argument throws a
TypeError, as does an engine that isn't a
GAMEPALETTE.Engine. The sprite starts with
scaleX and
scaleY at 1.
The animation starts on frame 0. With
randomizeStartFrame true, it starts at a random point
in the animation instead, so that a crowd of sprites sharing one
image (a field of flickering torches, say) don't all move in
step.
A new sprite is not active: it isn't drawn until you set its
isActive to
true. Sprites are usually created in a "setupGame"
logic function, once the images have loaded, as in the
Simple sprite control
demo:
s.ufo = new GAMEPALETTE.Sprite(s.engine, s.ufoImage, 0, 0);
s.ufo.isActive = true;
Setting a property to a value of the wrong type throws
a TypeError, and to a value out of range
a RangeError; in either case the property keeps its
old value. Changes show from the next frame drawn.
Whether the sprite is in the game. An active sprite is drawn every frame and its animation plays. An inactive one is neither drawn nor animated, but keeps all its settings, including its place in the animation, so turning it on again brings it back just as it was. Any value is accepted and treated as true or false.
Turn sprites off rather than leaving them out of sight: a
sprite that has been collected, destroyed, or has left the level
costs nothing while it's inactive. Turning a sprite off also takes
it out of the engine's
autoCameraSprite
list. The engine's
saveState
saves every active sprite, and
loadState
turns off any sprite that isn't in the save.
x and y
passed to the constructor
The sprite's position in the game world, in pixels: x
increases to the right and y downwards, as on the
canvas. The image's handle (see
handleOffsetX)
is placed here. Where that appears on the canvas depends on the
camera: with the camera at (0, 0), unturned, the point (0, 0) is
the center of the canvas (see
cameraX and
worldToCanvas).
Fractions are fine, and are drawn smoothly. To move a sprite,
change these in a logic function, by a few pixels each step for
steady movement:
if(s.keyRight.isPressed) s.ufo.x += 4;
The sprite's depth. Larger z is farther away, so sprites are drawn in order of z, largest first, and nearer sprites cover farther ones: give a backdrop a large z and the player a small one. Sprites with the same z are drawn in the order they were made active, the most recently activated on top. Changing z puts the sprite in its new place in the order straight away. Negative values are fine.
When the engine's
perspectiveView
is on, z also sets the sprite's size and how fast it scrolls by:
see
perspectiveScale.
The Parallax demo lets you move its
UFO in z with the Z and X keys.
rotation passed to the
constructor, or 0
How far the sprite is turned, in radians (a full turn is
2 * Math.PI), about its image's handle. Increasing it
turns the sprite clockwise. The value isn't wrapped to one turn.
To move a sprite in the direction it's facing (where an unturned
sprite faces right, along x):
s.ship.x += Math.cos(s.ship.rotation) * speed;
s.ship.y += Math.sin(s.ship.rotation) * speed;
The Linked sprites demo turns its robot with Q and E.
How much the sprite is stretched across (scaleX)
and up and down (scaleY), about its image's handle.
1 is its normal size, 2 twice the size, and 0.5 half. A negative
scale flips the sprite: scaleX = -1 mirrors it left to
right, which turns a sprite facing right into one facing left with
the same image. 0 squashes it to nothing. Scaling happens before
rotation, so the stretch turns with the sprite. Perspective (see
z) scales the sprite
further. The Fill renderers
demo zooms its sprite with C and Z.
alpha passed to the
constructor, or 1
How opaque the sprite is drawn: 1 is solid, 0 invisible, and
0.5 half see-through. It applies on top of any transparency in the
image itself. Values outside 0 to 1 are moved to the nearer end
rather than refused, so a fade can simply add or subtract a little
each step. An invisible sprite is still drawn (to no effect); turn
it off with isActive
when it's gone for good.
// Fade out over a second at 30 steps a second
s.ghost.alpha -= 1 / 30;
image passed to the
constructor
The image the sprite shows. Setting a new one starts its
animation from the first frame (keeping any fraction of a frame
already played, so the timing stays even), and sets the sprite's
handle and size to the new image's. Changing image is how a sprite
changes what it's doing: standing, walking, jumping. Setting the
image it already has also restarts the animation. An image's
onComplete can
change a sprite's image by itself when an animation ends.
if(s.keyRight.isPressed && s.player.image !== s.walkImage) {
s.player.image = s.walkImage;
}
null means no image, for sprites whose renderer
doesn't need one, such as the
textRenderer.
Anything else that isn't a GAMEPALETTE.Image throws
a TypeError.
frameCount
Where the sprite is in its image's animation, counted in frames
from 0. It moves on by itself as the animation plays (see
frameRate), so
it usually has a fraction: 2.6 means frame 2 is showing, six
tenths of the way to frame 3. Set it to jump to a frame, for
example to show one frame of a still image that holds several
pictures. A frame set by your code doesn't fire the image's
triggers; only the
animation reaching a frame does.
A value less than 0, or not less than the image's
frameCount,
throws a RangeError, and one that isn't a finite
number, a TypeError. (For a sprite without an image,
any value from 0 up is accepted.)
renderer passed to the
constructor, or
GAMEPALETTE.singleImageRenderer
The function that draws the sprite. The default,
GAMEPALETTE.singleImageRenderer, draws the current
frame of its image. The library's other renderers draw text or
repeat the image to fill the view, and you can write your own; see
Sprite Renderers. It can
be changed at any time; the Fill
renderers demo switches between three with the 1, 2, and 3
keys. Anything other than a function throws
a TypeError.
rendererParameter
passed to the constructor, or null
Extra information for the sprite's
renderer, if it
needs any. What it should be depends on the renderer: the
textRenderer
takes an object giving the text, font, and color, and the
CheckerboardMap add-on's renderer takes the map to draw. The
image renderers don't use it. Any value is accepted; it's up to
the renderer to make sense of it. If the game is saved with
saveState,
this is saved with the sprite.
Moves the sprite to (x, y) in one
call, and optionally to depth z and to
rotation; leave either out (or pass
null) to keep it as it is. It is the same as setting
x,
y,
z, and
rotation one at
a time, and checks each in the same way. The values are set in
that order, so if one is refused, those before it have already
changed.
s.ball.move(0, 0); // back to the middle
s.ball.move(0, 0, 10, Math.PI); // also farther away, upside down
A renderer is the function that draws a sprite. Each sprite has
one (its renderer
property), and many sprites can share one. The library provides
five, listed below, and the CheckerboardMap add-on a sixth,
GAMEPALETTE.checkerboardTileRenderer, which draws a
map of tiles (see
checkerboardmap.html and
the
Checkerboard map demo).
Any function that follows the rules below can be a renderer, so
you can draw sprites any way the canvas allows.
For each active sprite, in order from farthest to nearest, the engine calls its renderer as
renderer(engine, sprite)
with the engine and the sprite to draw. The renderer draws with
the engine's canvas context,
engine.cc. Before
calling it, the engine sets the context up so the renderer can draw
in the sprite's own coordinates:
globalAlpha is the sprite's
alpha.A renderer reads what it needs from the sprite: its
image and
frame, and its
rendererParameter
for anything else. It should only draw: change the game in logic
functions, since a sprite is drawn once per frame, not once per
step. It runs for every active sprite in every frame, so keep it
quick. To draw a frame of an image, use the image's
drawFrame, which
draws nothing until the image has loaded; to draw it any other way,
check isImageLoaded
first. A renderer that draws something large can draw only the
part on the canvas, found with the engine's
visibleArea.
A renderer can come in an add-on (see
Add-Ons). To save a game whose sprites use a renderer of
your own, give the renderer a name with the engine's
addSaveName.
This one draws a colored circle, its color and radius given by the
sprite's rendererParameter:
function circleRenderer(engine, sprite)
{
let parameter = sprite.rendererParameter;
engine.cc.fillStyle = parameter.color;
engine.cc.beginPath();
engine.cc.arc(0, 0, parameter.radius, 0, 2 * Math.PI);
engine.cc.fill();
}
s.ball = new GAMEPALETTE.Sprite(s.engine, null, 0, 0, 0,
circleRenderer,
{color: "orange", radius: 20});
The default renderer: draws the sprite's current
frame of its
image, with its
handle at the sprite's position. It draws nothing if the sprite
has no image, or the image hasn't loaded (or failed to). It
doesn't use the rendererParameter. Nearly every
sprite in the demos uses it.
Draws a line of text instead of an image. The sprite's
rendererParameter
says what to draw, as an object with these properties:
text: what to write. Anything is accepted and
turned into a string, so a number such as a score can be given
directly. If text is missing or null
(or the rendererParameter itself is), nothing is
drawn.font (optional): a CSS font, such as
"24px monospace" or "bold 16px serif".
The default is "16px Sans-Serif".color (optional): a CSS color, such as
"yellow" or "rgb(255, 128, 0)". The
default is white.The text is drawn in one line, starting at the sprite's position
and sitting on it as on a line of writing: the left end of the
text's baseline is at (x, y). Give the
sprite no image (null). Like any sprite, it moves with
the camera and can be turned, scaled, and faded; for a score or
message that stays put on the screen, draw it in the engine's
foregroundFunction
instead. To change the text, change the
rendererParameter's properties:
s.label = new GAMEPALETTE.Sprite(s.engine, null, 100, -50, 0,
GAMEPALETTE.textRenderer,
{text: "Treasure!", font: "20px serif",
color: "gold"});
s.label.isActive = true;
...
s.label.rendererParameter.text = "Taken";
Repeats the sprite's current frame endlessly in every direction,
filling the whole view, for a backdrop of grass, water, or stars
that never runs out however far the camera goes. Give the sprite a
large z so it's drawn
behind everything else.
The tiles are laid out in the sprite's own coordinates: one
tile is where the image would be drawn by the
singleImageRenderer,
and the rest are lined up with it. So moving the sprite slides the
pattern, and turning or scaling the sprite turns or scales the whole
pattern, without gaps or seams. It is drawn in a single operation,
and only the part on the canvas, so it costs about the same however
it's turned or zoomed. When a tile would be smaller than one pixel
on the canvas (the sprite scaled almost to nothing), it draws
nothing. It draws nothing either until the image has loaded, or
if the image's size is 0. It doesn't use the
rendererParameter. The
Fill renderers demo shows it
with every kind of movement.
Like the
tileFillRenderer,
but repeats the frame in one row only, endlessly to the left and
right along the sprite's x direction: a road, a fence, a strip of
ground, or a row of clouds. The row is one tile tall, in the same
place as the image drawn by the
singleImageRenderer,
and it turns with the sprite. In every other way it works like the
tileFillRenderer. Press 2 in the
Fill renderers demo to see
it.
Like the
horizontalFillRenderer,
but repeats the frame in a single column, endlessly up and down
along the sprite's y direction: a ladder, a waterfall, or a tower
wall. The column is one tile wide. Press 3 in the
Fill renderers demo to see
it.
A KeyInput is one control in your game, such as "move left" or
"fire", bound to one or more keys on the keyboard. Your logic
functions can ask whether it's held down
(isPressed),
and it can call a function of yours the moment it's pressed or
released: its
keyDownFunction
and
keyUpFunction.
Binding several keys to one KeyInput lets players use whichever they
like, such as W or the up arrow. Create your key inputs in your
"setupGame" logic function, as every demo does.
new GAMEPALETTE.KeyInput(engine, key, areaX = null, areaY = null,
areaWidth = null, areaHeight = null)
Creates a key input for engine (your
GAMEPALETTE.Engine), bound to the key
or keys given by key (see
key). The area
arguments set the properties of the same names, which are not yet
used (see areaX).
An unacceptable argument throws a TypeError, as does an
engine that isn't a GAMEPALETTE.Engine. The new key
input works straight away, and keeps working until its
deleteSelf
is called. From the
Linked sprites demo:
s.keyUp = new GAMEPALETTE.KeyInput(s.engine, ["KeyW", "ArrowUp"]);
s.keyRotateLeft = new GAMEPALETTE.KeyInput(s.engine, "KeyQ");
Setting a property to a value of the wrong type throws
a TypeError, and the property keeps its old value.
key passed to the
constructor
The keys this input is bound to, each named by its key code: the
browser's name for the key's position on the keyboard, such as
"KeyA", "Digit1", "ArrowLeft",
"Space", "Enter", or
"ShiftLeft". Codes name the key, not the character it
types, so they don't change with Shift or Caps Lock, and on
keyboards with other layouts they name the key in the same place
("KeyW" is the key above "KeyS" on any
keyboard). To find a key's code, press it on the
key code utility page.
GAMEPALETTE.anyKey is an array of the codes of nearly
every key, for "press any key".
Set it to one code as a string or to several as an array; it
always reads back as an array (a copy, so changing it has no
effect). The input counts as pressed while any of its keys is held.
Codes are case-sensitive, and a code that matches no key is accepted
but never pressed. Several key inputs may share a key, and all of
them respond to it. When the keys are changed, keys that are no
longer bound stop counting as held. Anything other than a string or
an array of strings throws a TypeError.
true while at least one of the input's keys is held
down, and false once all are released. Check it in a
logic function for things that happen for as long as a key is held,
such as moving:
if(s.keyLeft.isPressed) s.player.x -= 4;
A quick tap that starts and ends between two steps may be missed
this way; for things that should happen once per press, such as
jumping or firing, use
keyDownFunction.
Key presses are ignored while the player is typing in a text box or
other form field on the page. When the window loses focus, every
key counts as released (see the engine's
pauseOnWindowBlur),
since the browser doesn't report keys released elsewhere.
Functions called the moment the input is pressed
(keyDownFunction) and released
(keyUpFunction), with no arguments. "Pressed" means
the first of its keys going down, and "released" the last coming
up, so holding W and the up arrow together calls each function only
once. Holding a key down doesn't call keyDownFunction
again as the keyboard repeats. keyUpFunction is also
called if the input is held when the window loses focus.
null means no function. Anything else that isn't a
function throws a TypeError.
These are called as soon as the browser reports the key, between the engine's steps, and even while the engine is stopped, which makes them right for a pause key. The Linked sprites demo saves and loads its game this way.
s.keyPause = new GAMEPALETTE.KeyInput(s.engine, "KeyP");
s.keyPause.keyDownFunction = () =>
{
s.engine.isRunning = !s.engine.isRunning;
};
While the engine is running, keys bound to a key input don't also do what they normally would on the page, such as the arrow keys and space bar scrolling it.
A rectangle on the canvas, given by its top-left corner
(areaX, areaY) and size. These are kept
for a future version, in which tapping or clicking in the rectangle
will count as pressing the input, for touch-screen controls. For
now they are stored but have no effect. Each may be a finite number
or null (undefined is taken as
null); anything else throws
a TypeError.
true when all four area properties
(areaX and the
rest) are set to numbers, and false if any is
null. Like the area itself, it has no effect yet.
Returns the input's key codes as an array, the same as reading
key.
Takes the key input out of the engine, for a control the game no
longer needs (one for a level that's over, say). Afterwards it is
never pressed, its keyDownFunction and
keyUpFunction are no longer called, and it can't be
brought back; make a new one instead. If it was held at the time,
its keyUpFunction isn't called. Calling it again does
nothing.
A Sound is a sound effect or a piece of music, loaded from a
sound file. Calling its
play function plays
it. It can loop, play over itself, cross-fade, change speed and
pitch, be paused, fade in and out, belong to a category whose volume
is set together, and call functions of yours at chosen moments
(triggers). A sound can
also hold several recordings of the same thing (several footsteps,
say), and pick one at random each time it plays, so repeated
effects don't sound mechanical. The
Sound demo lets you try every feature
and shows the code for each action.
Sound plays only while the engine is
running. Browsers also hold
back all sound until the player has interacted with the page (a
click, a tap, or a key press); until then, sounds wait, with their
time standing still, and start the moment the player does. A game
usually begins with a title screen that asks for a key press anyway.
Sound files are loaded with the browser's fetch, so
the game must be on a web server: sounds don't load from a page
opened straight from a file on your computer.
Volumes multiply together: what you hear from a sound is its own
volume, times its
category's volume, times the
engine's
masterVolume.
Times are in seconds, on a sound clock that runs only while the
engine runs, so fades and triggers pause with the game.
new GAMEPALETTE.Sound(engine, soundURLs, category = null)
Creates a sound for engine (your
GAMEPALETTE.Engine) and starts
loading its sound files, given by soundURLs, which can
be:
"jump.mp3";["step1.mp3", "step2.mp3", "step3.mp3"];[["theme.ogg", "theme.mp3"]] (note the double
brackets: one recording, two formats). Whether a format can be
played is judged from the file's extension. If the browser can't
play any of them, that recording is left out and the formats are
listed in the engine's
loadErrors.category sets the sound's
category. More
recordings can be added later with
addSound. A URL
that isn't a non-empty string throws a TypeError, as
does an engine that isn't a GAMEPALETTE.Engine.
The files load in the background, and each counts toward the
engine's
loadProgress.
A file that can't be loaded or decoded is left out (its URL goes in
loadErrors), and the sound plays its other recordings;
with none left, play does nothing. The sound can be
played before its files have loaded: it starts as soon as they
arrive.
s.jumpSound = new GAMEPALETTE.Sound(s.engine, "jump.mp3", "effects");
s.music = new GAMEPALETTE.Sound(s.engine, [["theme.ogg", "theme.mp3"]],
"music");
s.music.loopSound = true;
Setting a property to a value of the wrong type throws
a TypeError, and to a value out of range
a RangeError; in either case the property keeps its
old value.
Each call to play
starts a new instance of the sound: one playing of it, from
the beginning. Usually there is one at a time, but there can be
several, overlapping (see
allowSimultaneousPlay),
and during a cross-fade the old instance fades out as the new one
fades in. Settings such as volume and playback rate belong to the
sound and apply to all its instances.
true once all the sound's files have finished
loading, or failed to (see the engine's
loadErrors),
and false while any are still loading. It becomes
false again while files added with
addSound load.
To wait for all of a game's sounds and images at once, use the
engine's
loadProgress.
true from the moment
play is called until
every instance of the sound has finished, faded out, or been
stopped. That includes instances that are
paused, waiting for the sound
to load, or waiting for the engine or the browser to let sound
start. A looping sound plays until
stop is called.
How many instances of the sound are under way: playing, paused,
or waiting to start, and including any fading out. With
allowSimultaneousPlay
on, it can be more than 1; use it to keep a sound from piling up,
for example by not playing it again while three are going. The
next pass of a looping sound, which is set up a moment before it's
due, isn't counted until it begins.
Set it to true to pause the sound: every instance
stops where it is, and false carries each on from the
same place. A sound played while paused waits, and starts when
unpaused. This is separate from the engine stopping (see
isRunning),
which halts all sound and then resumes the sounds that aren't
paused here; so you can pause the music for a moment in the game
without it starting again by itself. Any value is accepted and
treated as true or false.
When true, the sound plays over and over until
stop is called, for
music or background noise such as wind or engines. Calling
play while it's
already playing does nothing, so it's safe to call on every
step. Each pass plays the same recording, picked when it started.
With
simultaneousCrossFadeRate
at 0, the loop is seamless, with no gap or click, for recordings
made to loop; above 0, each pass cross-fades into the next, which
smooths over a recording that doesn't quite loop.
It can't be changed while the sound is playing, and can't be on
together with
allowSimultaneousPlay;
either throws an Error. Any value is accepted and
treated as true or false.
What happens when the sound is played while it's already
playing. When true, each
play starts another
instance alongside the others, so the sounds overlap: right for
gunshots, coins, and footsteps that come quickly. When
false, a new play starts the sound again
from the beginning, cross-fading from the instance that was playing
over
simultaneousCrossFadeRate
seconds (at least a hundredth of a second, to avoid a click), so
only one plays at a time.
It can't be changed while the sound is playing, and can't be on
together with
loopSound;
either throws an Error. Any value is accepted and
treated as true or false.
The length of the sound's cross-fades, in seconds (despite the
name, it's a time, not a rate). It's used in two places: when the
sound is played again while playing, with
allowSimultaneousPlay
off, the old instance fades out and the new one fades in over this
time; and with
loopSound on,
each pass of the loop fades into the next over this time (at most
half the recording's length), instead of looping seamlessly.
It must be less than
maximumCrossFadeRate,
the length of the shortest recording, once that is known; a value
that isn't throws a RangeError, and so does a negative
one. It can't be changed while the sound is playing (an
Error).
The length, in seconds, of the shortest of the sound's
recordings that has loaded, or null before any has.
simultaneousCrossFadeRate
must be less than this, since a cross-fade can't be longer than
the sound. It's also a handy way to find out how long a sound
is.
The sound's own volume, from 0 (silent) to 1 (full). It applies
to every instance at once, including those already playing, and is
multiplied by the sound's category volume and the engine's
masterVolume.
Values outside 0 to 1 are moved to the nearer end rather than
refused. To change it gradually, use
fadeVolume;
reading volume during a fade gives the volume at that
moment, and setting it cancels the fade. The engine's
saveState
saves it.
How fast the sound plays: 1 is normal, 2 twice as fast, and 0.5
half as fast. Speed and pitch go together, as on a record player:
twice as fast is an octave higher. It applies straight away to the
instances playing and to later ones. Raising it bit by bit as a
car speeds up, say, makes an engine sound rev. To change it
gradually, use
fadePlaybackRate;
setting playbackRate cancels such a change. A value
that isn't a finite number greater than 0 throws
a RangeError. Trigger times (see
addTrigger)
are positions in the recording, so they come sooner at a faster
rate.
A random change of pitch for each play, so that a sound repeated
often (footsteps, hits, coins) doesn't sound the same every time.
Each instance picks its own pitch, up to this many semitones above
or below the
playbackRate,
and keeps it; speed changes with pitch, as always. 1 or 2
semitones is usually plenty; 12 is an octave. 0 turns it off. A
loop keeps the pitch its first pass picked. A value that isn't a
finite number of 0 or more throws a RangeError.
category passed to the
constructor, or null
The name of the group the sound belongs to, such as
"music" or "effects", or
null for none. The volume of a whole category is set
with the engine's
setCategoryVolume
and
fadeCategoryVolume,
which makes separate music and effects volume controls easy. A
category comes into being when its first sound joins it, at full
volume, and is forgotten when its last sound leaves (see
soundCategories).
The sound can change category at any time, even while playing; it
takes on the new category's volume at once. Anything other than a
string or null throws a TypeError.
Plays the sound from the beginning, picking one of its recordings
at random if it has more than one. What happens if it's already
playing depends on its settings: a looping sound
(loopSound)
carries on and the call does nothing; with
allowSimultaneousPlay
on, another instance starts alongside; otherwise the sound starts
again, cross-fading from the instance that was playing (see
simultaneousCrossFadeRate).
The sound doesn't always start at once. If it's paused, it starts when unpaused; if its recording hasn't loaded yet, when it has; and if the engine is stopped, or the browser is still holding back sound, when that changes. If none of its recordings could be loaded, it does nothing. It returns nothing.
s.keyJump.keyDownFunction = () => s.jumpSound.play();
Stops every instance of the sound at once, without a fade, and
forgets them: the next
play starts from the
beginning. This is how a looping sound is ended. Triggers not yet
reached aren't fired. The sound's settings, including
isPaused, are
unchanged. To end a sound gently, fade it out with
fadeVolume
first and stop it once the fade is done (perhaps with a
trigger).
Changes the sound's
volume gradually,
in a straight line from its current value to
targetVolume over duration seconds: for
example, s.music.fadeVolume(0, 3) fades the music out
over three seconds. It affects all the sound's instances. A
targetVolume outside 0 to 1 is moved to the nearer end.
A new fade replaces one already under way, starting from wherever
that one had got to, and setting volume cancels it.
Fades pause while the engine is stopped. Fading to 0 leaves the
sound playing silently; call
stop to end it. A
targetVolume that isn't a finite number throws a
TypeError, and a duration that isn't a
finite number greater than 0, a RangeError.
Changes the sound's
playbackRate
smoothly from its current value to targetRate over
duration seconds, in a straight line, affecting the
instances playing and any started meanwhile: a record slowing to a
stop, or a siren winding up. A new change replaces one under way,
and setting playbackRate cancels it. It pauses while
the engine is stopped. A targetRate or
duration that isn't a finite number greater than 0
throws a RangeError.
Adds a trigger: from now on, whenever an instance of the sound
reaches time seconds into its recording, the engine
calls the function trigger, with no arguments. Use it
to time things to the sound: flash the screen on the beat of a
drum, show a word as it's spoken, or start the next piece of music
as one ends. Returns the trigger's id, a whole number for
removeTrigger.
Each instance fires each trigger once as it passes the time, so
with overlapping instances a trigger fires once for each; a looping
sound fires its triggers again on every pass. A trigger added
while the sound is playing fires for the instances now playing only
if they haven't yet passed its time. A time of 0 fires as the sound
starts; a time beyond the end of the recording never fires, and a
time at the very end fires as the sound finishes. An instance
stopped with stop
fires no more triggers.
The time is a position in the recording, so at a faster
playbackRate
it comes sooner. Triggers are checked 40 times a second while the
engine runs, so one may fire up to about a fortieth of a second
late, which is too little to notice. They don't fire while the
engine is stopped or the sound paused. A trigger may play or stop
sounds, including this one. A time that isn't a finite
number throws a TypeError, and a negative one,
a RangeError; a trigger that isn't a
function throws a TypeError.
// The intro is 12.5 seconds long; as it ends, start the main theme
s.intro.addTrigger(12.5, () => s.theme.play());
See it in use in the Sound triggers demo.
Removes the trigger with the id triggerId, as
returned by
addTrigger,
from the sound and from any instances playing, so it no longer
fires. A triggerId that isn't a whole number throws
a TypeError, and one that isn't the id of one of the
sound's triggers (perhaps already removed), a
RangeError.
Adds more recordings to the sound, from soundURLs
in any of the forms the
constructor accepts. From
then on, each play
picks at random among all the recordings. The new files load in
the background and count toward the engine's
loadProgress.
A URL that isn't a non-empty string throws a
TypeError.
Takes the sound out of the game, for one that's no longer
needed: it stops playing, leaves its category (which disappears if
this was its last sound), and is removed from the engine, so the
engine's saveState
no longer includes it. Don't play it afterwards; make a new sound
instead.
These functions belong to GAMEPALETTE itself, not to
an engine, since an add-on is loaded once for the whole page. They
are used by add-on files to tell the library about themselves, and
by games to find out which add-ons are loaded. See the
Add-Ons chapter for how to write an
add-on.
Adds an add-on to the library. An add-on file calls it once, as
it loads. definition is an object with these
properties:
name: the add-on's name, a non-empty string,
different from every other add-on's.version (optional): its version, a string.requires (optional): an array of the names of the
add-ons it needs, which must already have been added.engineCreated, beforeLogicStep,
afterLogicStep, beforeDraw,
afterDraw, afterLoadState (each
optional): the add-on's hooks, functions the engine calls, with
the engine as their argument, at the moments described in
Hooks.If the add-on has an engineCreated hook, it is
called at once for each engine that already exists, and later for
each new one. The definition is checked before anything is added,
so a call that fails changes nothing. A definition
that isn't an object, one with any other property (such as a
misspelled hook), a name, version, or
requires of the wrong kind, or a hook that isn't a
function throws a TypeError. A name
that's already taken, or a requires naming an add-on
that hasn't been added, throws an Error. It returns
nothing.
GAMEPALETTE.addAddOn({
name: "Radar",
version: "1.0",
requires: ["Mover"],
afterDraw(engine)
{
// Draw a dot in the corner for each active sprite
}
});
Returns true if an add-on named name has
been added, and false if not. A game can use it to
check that the add-ons it needs are loaded, or to use an add-on only
when it's there.
if(GAMEPALETTE.hasAddOn("LinkedSprite") == false) {
alert("Please load linkedsprite.js");
}
Returns an array describing the add-ons that have been added, in
the order they were added, each as an object
{name, version, requires}: the add-on's name, its
version (or null if it gave none), and the array of the
add-ons it requires. The array and its objects are copies, so
changing them has no effect. With both of Game Palette's add-ons
loaded, it returns
[{name: "LinkedSprite", version: "1.0", requires: []},
{name: "CheckerboardMap", version: "1.0", requires: []}]