This documentation does not document all of Sprite.js features, but only those that are considered stable.
The scene object is a DOM container where all the Sprites will be drawn. You always need to start by creating a Scene object.
// create a Scene object
var scene = sjs.Scene({w:640, h:480});
Create a new Scene.
Options details:
DOM parent of the scene. The default is document.body.
Width of the scene.
Height of the scene.
Pause the scene when the user quit the current window. The default is true.
This is the list of the different methods available on the Scene object:
| Arguments: |
|
|---|
Load the given array of image sources. When all images are loaded, the callback is executed.
Delete all layers present in this scene, delete the sprites and layers, and pause the ticker.
Create a Layer object, see the Layer section.
| Arguments: |
|
|---|
Create a Sprite object, see the Sprite section.
| Arguments: |
|
|---|
Create a Ticker object for this scene or reset the previous one.
| Arguments: |
|
|---|
Alias for sjs.Cycle, see the Cycle section.
Alias for sjs.Input, see the Input section.
To create a sprite you should use the Scene.Sprite constructor:
| Arguments: |
|
|---|
A Sprite can be instantiated from different objects and with a range of options. eg:
var foreground = scene.Layer("foreground");
var player = scene.Sprite("player.png", foreground);
You can create the sprite using the Layer directly instead of the Scene:
var foreground = scene.Layer("foreground");
var player = layer.Sprite("player.png");
You can also initialize any Sprite properties by passing an options object instead of the Layer object, eg:
var options = {layer:layer, x:10, size:[20, 20], y:15};
var sprite = scene.Sprite("mysprite.png", options);
All parameters are optional. If the layer is not specified, the default layer will be used. If you want to set the layer but not any image you can do so like this:
var sprite = scene.Sprite(false, {layer:layer, color:"#f11"});
To update any visual changes to the view you should call the update method:
Apply the latest changes to the sprite’s layer.
| Arguments: |
|
|---|
Change the image sprite.
Remove the DOM element if the HTML engine is used and enable the garbage collection of the object.
Draw the sprite on a given Canvas layer. This doesn’t work with an HTML layer.
With a canvas engine, the surface will be automatically cleared before each game tick. You will need to call update to draw the sprite on the canvas again. If you don’t want to do this you can set the layer autoClear attribute to false.
For technichal and performance reasons a Sprite’s attributes needs to be changed using a setters method. The following attributes are READ ONLY:
The horizontal position of the sprite as measured against the top left corner of the scene.
The vertical position of the sprite as measured top left corder of the scene.
Controls the horizontal visible surface of the image. To have a repeating sprite background you can set the width or height value bigger than the size of the image.
Controls the vertical visible surface of the image.
The horizontal offset within the sprite’s image from where to start painting the sprite’s surface.
The verical offset within the sprite’s from where to start painting the sprite’s surface.
Horizontal scaling.
Vertical scaling.
Rotation of the sprite in radians.
Background color of the sprite. Use the rgb/hexadecimal CSS notation.
If you want to change any of those attributes use the following setters:
Or one of those helper methods:
If y is not defined, y will take the same value as x.
Move the sprite in the direction of the vector (x, y) argument.
Set the position of the sprite (left, top)
Set the width and height of the visible sprite.
Sprites have methods to help you implement a basic physics engine:
Horizontal velocity.
Vertical velocity.
Radial velocity
Apply all velocities on the current Sprite.
Reverse all velocities on the current Sprite.
Apply the horizontal xv velocity.
Apply the vertical yv velocity.
Apply the horizontal xv velocity negatively.
Apply the vertical yv velocity negatively.
Rotate the velocity vector according to the provided angle.
Point the velocity vector in the direction of the point (x, y). The velocity intensity remains unchanged.
Returns the distance between the calling sprite’s center and it’s argument sprites center.
Return the distance between the sprite’s center and the point (x, y)
These methods are not included in the sprite.js core and needs to be loaded indenpendantly:
<script src="lib/collision.js"></script>
Returns true if the point (x, y) is within the sprite’s surface.
Returns true if the sprite is in collision with the passed sprite
| Arguments: |
|
|---|
Searches the passed array of sprites for a colliding sprite. If found, that sprite is returned.
There are two methods useful for creating special effects. You can use explode2 to separate the current sprite in two parts:
| Arguments: |
|
|---|
Returns an array of two new sprites that are the two parts of the sprite according to the given position. The default value for position is half the size of the sprite.
| Arguments: |
|
|---|
Return an array of four new sprites that are the split from the center (x, y). The default value for (x, y) is the center of the sprite.
A List is an iterable object that simplifies the management of an sprite (or any other object) array:
| Arguments: |
|
|---|
Create the object list.
Add an object or an array of objects to the list.
Remove the first matching object from the list.
Returns an object and increment the pointer. Returns false at the end of the list.
The length of the list.
Returns the underlying array that the List is managing.
Example of use:
var crates = sjs.List([crate1, crate2]);
var crate;
while(crate = crates.iterate()) {
crate.applyVelocity();
if(crate.y > 200) {
// remove it from the list
crates.remove(crate);
// remove it from the DOM
crate.remove();
}
}
Keeping track of time in javascript can be difficult. Sprite.js provides a Ticker object to deal with this issue.
A Ticker is an object that keeps track of time properly, so it’s straight forward to render the changes in the scene. The Ticker gives accurate ticks. A game tick is the time between every Sprites/Physics update in your engine. To setup a ticker:
function paint(ticker) {
myCycles.next(ticker.lastTicksElapsed);
// do your animation and physics here
}
var ticker = scene.Ticker(paint);
| Arguments: |
|
|---|
Start the ticker.
Pause the ticker.
Resume after a pause.
lastTicksElapsed is the number of ticks elapsed during two runs of the paint function. If performances are good the value should be 1. If the number is higher than 1, it means that there have been more game ticks than calls to the paint function since the last time paint was called. In essence, there were dropped frames. The game loop can use the tick count to make sure that it’s physics end up in the right state, regardless of what has been rendered.
The number of elapsed ticks that have been occurred since the creation the the ticker.
A Cycle object manages sprite animations by moving the offsets within the viewport of the sprites.
This is an example cycle with 3 different offset, each lasting 5 game ticks:
var cycle = scene.Cycle([[0, 2, 5],
[30, 2, 5],
[60, 2, 5]);
var sprite = scene.Sprite("walk.png");
cycle.addSprite(sprite);
cycle.update();
cycle.next(5).update();
Cycle complete reference:
| Arguments: |
|
|---|
| Arguments: |
|
|---|
| Arguments: |
|
|---|
| Arguments: |
|
|---|
| Arguments: |
|
|---|
Calling the next method doesn’t necessarily involve an offset change. It does only when all the ticks on current triplet have been consumed.
| Arguments: |
|
|---|
| Arguments: |
|
|---|
Resets the cycle offsets to the original position.
Calls the update method on all the sprites.
This attribute can be checked to determine if the cycle has completed. The value stays false if cycle is repeating.
If set to false, the cycle will stop automaticaly after one run. The default value is true.
The input object remembers user inputs within each game tick:
var input = scene.Input();
if(input.keyboard.right) {
sprite.move(5, 0);
}
if(input.keyboard.z)
console.log("Key z is down")
Creates an Input object for the scene.
Input.keyboard is a record of which key has been pressed or released. In addition to the normal keyboard keys, the keyboard object also keep track of these special keyboard states:
keyboard.up
keyboard.right
keyboard.up
keyboard.down
keyboard.enter
keyboard.space
keyboard.ctrl
keyboard.esc
True if any key is down.
True if any mouse button is down.
If you need to know which key has been pressed or released during the last game tick, use these methods:
| Arguments: |
|
|---|
| Arguments: |
|
|---|
The mouse object contains the position of the mouse and if the mouse is clicked.
if(mouse.position.x < scene.w / 2)
player.move(-2, 0);
if(mouse.click)
console.log(mouse.click.x, mouse.click.y);
A small swipe updates the keyboard in the wanted direction and a tap will act as the spacebar being pressed. The mouse position and clicks are also updated by the touch events.
If you need to separate your sprites into logical layers, you can crate a Layer:
var background = scene.Layer('background', {
useCanvas:true,
autoClear:false
});
var sprite = background.Sprite('background.png');
| Arguments: |
|
|---|
Create the Layer object.
If true this layer will use the canvas element to draw the sprites. This enables you to mix HTML and canvas.
If false this disables the automatic clearing of the canvas before every paint call.
Sets a different DOM parent instead of the scene.
Sprite.js provides the Input helper object for managing keyboard input. If you need more complex events handling the recommanded way is to use event delegation on the Scene object or a specific Layer object:
var scene = sjs.Scene({w:640, h:480});
var frontLayer = scene.Layer("front");
frontLayer.dom.onclick = function(e) {
var target = e.target || e.srcElement;
target.className = 'selected';
}
scene.dom.onclick = function(e) {
var target = e.target || e.srcElement;
target.className = 'selected';
}
If you need to use events on a Sprite level you can do it if you use the HTML engine:
sprite.dom.addEventListener('click', function(e) {
sprite.dom.className = 'selected';
}, true);
To use some of these feature, you must include an extra javascript files in your web page.
This object is not included in sprite.js core and needs to be loaded independantly:
<script src="lib/scrolling.js"></script>
This object provide a simple and efficent way to display a moving background within a scene. The object buffers parts that have already been drawn and only redraw the necessary parts instead of the whole scene at every frame.
var surface = sjs.SrollingSurface(scene, w, h, redrawCallback);
function redrawCallback(layer, x, y) {
// draw the necessary sprites on the layer
sprite.canvasUpdate(layer);
}
surface.move(5, 0);
surface.update();
The redrawCallback is called whenever a part of the surface needs to be updated. The absolute position on the surface is provided for you as an argument to redrawCallback so you may determine what to draw on this layer. The layer object has a width and height (layer.w, layer.h).
| Arguments: |
|
|---|
| Arguments: |
|
|---|
Moves the surface offset in direction (x, y).
Sets the surface offset position to (x, y)
Updates the latest changes to the surface and call the redrawCallback if necessary.
Sprite.js comes packaged with a few basic math functions:
Hypotenuse
A modulo function that return strictly positive result.
Return a normal vector {x, y}. If you define the intensity, the vector will be multiplied by it.
This object is not included in sprite.js core and needs to be loaded independently:
<script src="lib/path.js"></script>
Sprite.js has a flexible path finding function:
The algorithm return undefined if no path has been found and the startNode if a path is found. You can then follow the path using this code:
var node = sjs.path.find(startNode, endNode);
while(node) {
console.log(node);
node = node.parent;
}
A node object should implement those 4 methods:
Define your own Node object.
Must return a list of Nodes that are the neighbors of the current one.
Returns the distance from this node to another one. It’s mainly used as a hint for the algorithm to find a quicker way to the end. You may return 0 if you don’t want to implement this method.
Returns true if two nodes are identical, eg:
return this.x == node.x && this.y == node.y;
Returns true if the current node cannot be used to find the path.
If you wish to use a entity component model with Sprite.js I would recommend the use of this external library https://github.com/batiste/component-entity