Example 1. Spritesheet

A spritesheet can have multiple frames. This is an example sprite sheet with 4 frames:

The 32 by 32 image contains four 16 by 16 images of red, turqoise, rose and green blocks.



This is the main HTML file, ex01.html, using the Phaser gaming library:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Ex01</title>
  <script type="text/javascript" src="js/phaser.min.js"></script>
  <link rel="stylesheet" type="text/css" href="css/ex01.css">
</head>
<body>
  <div align="center" id="ex01"></div>
  <div align="center" id="frame"></div>
  <script type="text/javascript" src="js/ex01.js"></script>
</body>
</html>


This is the csv file, ex01.css:

1
2
3
4
5
6
7
8
9
#frame {
 width: 800px;
 margin: auto;
 font-family: "Arial";
 font-size: 96px;
 color: white;
 background: blue;
 text-align: center;
}


Finally the ex01.js JavaScript file is

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var game = new Phaser.Game(800, 600, Phaser.AUTO, 'ex01',
               { preload: preload, create: create});
var colorBox;

function preload() {
    game.load.spritesheet('fourColors', 'images/ex01.png', 16, 16, 4);
}

function create() {
    game.stage.backgroundColor = "#00FFFF";
    colorBox = game.add.sprite(game.world.centerX, game.world.centerY, 'fourColors');
    colorBox.scale.setTo(10,10);
    colorBox.anchor.setTo(0.5, 0.5);
    colorBox.inputEnabled = true;
    colorBox.events.onInputDown.add(changeColor, this);
    displayFrame(colorBox.frame);
}

function changeColor() {
    colorBox.frame = (colorBox.frame + 1) % 4;
    displayFrame(colorBox.frame)
}

function displayFrame(frame) {
    document.getElementById("frame").innerHTML = "frame = " + frame;
}


Two global variables are created, for the sprite and game. We make a sprite from the spritesheet. Frame 0 (red) is selected by default. We enable clicking on the sprite. When clicked, it recycles through another frame in range 0 to 3.


We also display the current frame in the #frame div. In the screenshot, we are at frame 3:

No comments:

Post a Comment