Phaser Tilemap Demo
by Josh Davison
HTML
<script src="https://github.com/photonstorm/phaser/releases/download/v3.9.0/phaser.min.js"></script>
<div>
<p>The tilemap should start on the left of the game. The floor layer should start on the left of the game. The background layer should start in the horizontal center of the viewport.</p>
<p>
I've use `backrgoundLayer.x = config.width/2`, but the problem is that doesn't just define where the tiles will start, it defines where the layer will render. As the player moves to the right, the background layer scrolls, but instead of going all the way across the viewport, the background layers tiles get culled when they reach the center of the viewport.
</p>
</div>
CSS
html, body {
margin: 0;
padding: 5vh;
min-height: 100vh;
overflow: auto;
box-sizing: border-box;
display: flex;
flex-direction: row;
flex-wrap: wrap;
align-items: center;
justify-content: center;
}
canvas {
margin: 0;
padding: 0;
}
body > * {
flex: 0 0 auto;
}
div {
max-width: 80vw;
}
JavaScript
var config = {
type: Phaser.AUTO,
width: 400,
height: 400,
physics: {
default: 'arcade',
arcade: {
gravity: {
x: 0,
y: 0
},
debug: false
}
},
scene: {
key: 'main',
preload: preload,
create: create,
update: update
}
};
var game = new Phaser.Game(config);
var demoObj1;
var demoObj2;
var demoObj3;
var demoBG;
var mainCamera;
var text;
var count = 0;
function preload() {
this.load.image('demoBG', 'https://image.ibb.co/mKX8rd/demoBG.png');
this.load.image('demoObj1', 'https://image.ibb.co/jFJRcJ/demoObj1.png');
this.load.image('demoObj2', 'https://image.ibb.co/hNtsHJ/demoObj2.png');
this.load.image('demoObj3', 'https://image.ibb.co/hNtsHJ/demoObj2.png');
}
function create() {
demoBG = this.add.image(0, 0, 'demoBG');
demoObj1 = this.physics.add.sprite(0, 10, 'demoObj1');
demoObj1.setCollideWorldBounds(true);
demoObj2 = this.physics.add.staticSprite(400, 100, 'demoObj2');
demoObj2.setCollideWorldBounds(true);
demoObj2.setScrollFactor(0.1, 1);
demoObj2.setOrigin(1);
demoObj3 = this.add.image(400, 100, 'demoObj3');
// demoObj3.setCollideWorldBounds(true);
demoObj3.setAlpha(0.25);
this.physics.world.bounds.width = config.width * 4;
this.physics.world.bounds.height = config.height;
cursors = this.input.keyboard.createCursorKeys();
mainCamera = this.cameras.main;
mainCamera.setBounds(0, 0, config.width * 4, config.height);
mainCamera.startFollow(demoObj1, false, 1, 1, 0, 100);
}
function update() {
if (cursors.left.isDown) {
demoObj1.body.setVelocityX(-400);
} else if (cursors.right.isDown) {
demoObj1.body.setVelocityX(400);
} else {
demoObj1.body.setVelocityX(0);
}
if (cursors.up.isDown) {
demoObj1.body.setVelocityY(-400);
} else if (cursors.down.isDown) {
demoObj1.body.setVelocityY(400);
} else {
demoObj1.body.setVelocityY(0);
}
}