BattleCity game using Phaser.IO, part 2 – move it!

In this part we will create our player tank, add animation of our moving tank (moving left, right etc) and perform actual tank movement on pressing of corresponding cursor keys.

In preload function we should load our spritesheet. Actually it is the same image as we used for tilesheet and same spritesheet will be used for our player and enemy tank sprites and animations.

[code lang=”js” htmlscript=”true”]
// load spritesheet for our player and enemies, all of them use same spritesheet
game.load.spritesheet(‘tanks’, ‘assets/tilemaps/tiles/battlecity_general.png’, 16, 16);
[/code]

Next we should declare some new variables, one for our player tanks and one for cursor keys.

[code lang=”js”]
var player_tank;
var cursors;
[/code]

In a create function we will create our player tank, define animations for our player tank movements.

Also here we will create object responsible for reading cursor keys. Enable our player tank physics, set scale of our player tank sprites.

[code lang=”js”]
//create cursor key handler
cursors = game.input.keyboard.createCursorKeys();

//create our player tank, position it at x,y and use sprite sheet ‘tanks’
player_tank = this.game.add.sprite(128, 448, ‘tanks’);
//enable physics for our player sprite so we could move it etc
game.physics.arcade.enable(player_tank);
//set initial frame for our player sprite
player_tank.frame = 0;
//scale our player sprite as all our world is scaled by 2
player_tank.scale.set(2);
//define movement animations for our player – up, down etc, provide sprite numbers, timing,
player_tank.animations.add(‘left’, [2,3], 10, true);
player_tank.animations.add(‘right’, [6,7], 10, true);
player_tank.animations.add(‘up’, [0,1], 10, true);
player_tank.animations.add(‘down’, [4,5], 10, true);
[/code]

In the update function we will perform checking if any of the cursor keys is pressed, and if it is, we will start corresponding animation and player tank movement.

[code lang=”js”]
if (cursors.left.isDown)
{
//if left cursor is down – play left animation, add velocity
player_tank.animations.play(‘left’);
player_tank.body.velocity.x = -100;
}
else if (cursors.right.isDown)
{
player_tank.animations.play(‘right’);
player_tank.body.velocity.x = 100;
}
else if (cursors.up.isDown)
{
player_tank.animations.play(‘up’);
player_tank.body.velocity.y = -100;
}
else if (cursors.down.isDown)
{
player_tank.animations.play(‘down’);
player_tank.body.velocity.y = 100;
}
else
{
player_tank.animations.stop();
player_tank.body.velocity.x = 0;
player_tank.body.velocity.y = 0;
}
}
[/code]

That`s it, if everything done correctly, then by pressing cursor keys you should be able to move your tank and this movement should be animated.

Be the first to comment

Leave a Reply

Your email address will not be published.


*