Phaser 3 simple platformer
JavaScript
const config = {
type: Phaser.AUTO,
width: 1024,
height: 513,
physics: {
default: 'arcade',
arcade: {
gravity: { y: 800 },
debug: false
}
},
scene: {
preload,
create,
update
}
};
const game = new Phaser.Game(config)
function preload() {
this.load.image('background', 'assets/background.jpg');
this.load.image('tiles', 'assets/tileset.png');
this.load.image('player', 'assets/character.png');
this.load.image("star", 'assets/star.png');
this.load.tilemapTiledJSON('level1', 'assets/level1.json');
}
function create() {
const backgroundImage = this.add.image(0, 0, 'background').setOrigin(0, 0);
backgroundImage.setScale(2, 0.8);
const map = this.make.tilemap({ key: 'level1'});
const tileset = map.addTilesetImage('tileset', 'tiles');
const platforms = map.createStaticLayer('Platforms', tileset, 0, 0);
this.player = this.physics.add.sprite(30, 300, 'player');
this.player.setBounce(0);
platforms.setCollisionByExclusion(-1, true);
this.player.setCollideWorldBounds(true);
this.physics.add.collider(this.player, platforms);
this.cursors = this.input.keyboard.createCursorKeys();
cursors = this.input.keyboard.createCursorKeys();
stars = this.physics.add.group({
key: 'star',
repeat: 11,
setXY: { x: 12, y: 0, stepX: 70 }
});
stars.children.iterate(function (child) {
child.setBounceY(Phaser.Math.FloatBetween(0.4, 0.8));
});
scoreText = this.add.text(16, 16, 'score: 0', { fontSize: '32px', fill: '#000' });
this.physics.add.collider(player, platforms);
this.physics.add.collider(stars, platforms);
this.physics.add.overlap(player, stars, collectStar, null, this);
}
function update() {
if (this.cursors.left.isDown) {
...