Example 3. Sprite

From now, we will have the standard html file below. The only difference would be the div id name and script name.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Ex03</title>
  <script type="text/javascript" src="js/phaser.min.js"></script>
</head>
<body>
  <div align="center" id="ex03"></div>
  <script type="text/javascript" src="js/ex03.js"></script>
</body>
</html>

This is the javascript file:




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Ex03. Sprite

var game = new Phaser.Game(800, 600, Phaser.AUTO, 'ex03',
               { preload: preload, create: create});
var ball;

function preload() {
    game.load.image('ball', 'images/ex03.png');
}

function create() {
    game.stage.backgroundColor = "#0FFF0F";
    var x = game.world.centerX;
    var y = game.world.centerY;
    ball = game.add.sprite(x, y, 'ball');
    ball.scale.setTo(2,2);
    ball.anchor.setTo(0.5, 0.5);
    game.input.onDown.add(changePosition, this);
}

function changePosition() {
    ball.x = game.input.activePointer.x;
    ball.y = game.input.activePointer.y;
}

A ball image is used:




Now by clicking anywhere on the screen, the ball moves there:



No comments:

Post a Comment