Newer
Older
<script>
class Example extends Phaser.Scene
{
showDebug = false;
player;
helpText;
debugGraphics;
cursors;
map;
preload ()
{
this.load.setBaseURL('https://raw.githubusercontent.com/Anbak98/phaser3/master/public/assets/');
this.load.image('tiles', 'Tilemap.png');
this.load.tilemapCSV('map', 'map.csv');
this.load.spritesheet('player', 'Arrow.png', { frameWidth: 16, frameHeight: 16 });
}
create ()
{
// When loading a CSV map, make sure to specify the tileWidth and tileHeight
this.map = this.make.tilemap({ key: 'map', tileWidth: 8, tileHeight: 8 });
const tileset = this.map.addTilesetImage('tiles');
const layer = this.map.createLayer(0, tileset, 0, 0);
// This isn't totally accurate, but it'll do for now
this.anims.create({
key: 'left',
frames: this.anims.generateFrameNumbers('player', { start: 2, end: 2 }),
frameRate: 10,
repeat: -1
});
this.anims.create({
key: 'right',
frames: this.anims.generateFrameNumbers('player', { start: 3, end: 3 }),
frameRate: 10,
repeat: -1
});
this.anims.create({
key: 'up',
frames: this.anims.generateFrameNumbers('player', { start: 0, end: 0 }),
frameRate: 10,
repeat: -1
});
this.anims.create({
key: 'down',
frames: this.anims.generateFrameNumbers('player', { start: 1, end: 1 }),
frameRate: 10,
repeat: -1
});
this.player = this.physics.add.sprite(50, 100, 'player', 1);
// Set up the player to collide with the tilemap layer. Alternatively, you can manually run
// collisions in update via: this.physics.world.collide(player, layer).
this.physics.add.collider(this.player, layer);
this.cameras.main.setBounds(0, 0, this.map.widthInPixels, this.map.heightInPixels);
this.cameras.main.startFollow(this.player);
}
update (time, delta)
{
this.player.body.setVelocity(0);
// Horizontal movement
if (this.cursors.left.isDown)
{
this.player.body.setVelocityX(-100);
}
else if (this.cursors.right.isDown)
{
this.player.body.setVelocityX(100);
}
// Vertical movement
if (this.cursors.up.isDown)
{
this.player.body.setVelocityY(-100);
}
else if (this.cursors.down.isDown)
{
this.player.body.setVelocityY(100);
}
// Update the animation last and give left/right animations precedence over up/down animations
if (this.cursors.left.isDown)
{
this.player.anims.play('left', true);
}
else if (this.cursors.right.isDown)
{
this.player.anims.play('right', true);
}
else if (this.cursors.up.isDown)
{
this.player.anims.play('up', true);
}
else if (this.cursors.down.isDown)
{
this.player.anims.play('down', true);
}
else
{
this.player.anims.stop();
}
}
const config = {
type: Phaser.AUTO,
width: 800,
height: 600,
backgroundColor: '#2d2d2d',
parent: 'phaser-example',
pixelArt: true,
physics: {
default: 'arcade',
arcade: {
gravity: { y: 0 }
}
},
scene: Example
};
const game = new Phaser.Game(config);
</script>
</body>