JSFiddle - React, Tailwind, and code Playground
JavaScript
var play1_state = {
// No more preload, since it is already done in the 'load' state
create: function () {
game.world.setBounds(0, 0, 2560, 480);
game.physics.startSystem(Phaser.Physics.P2JS);
map = game.add.tilemap('map');
map.addTilesetImage('tiles');
layer = map.createLayer('Tile Layer 1');
layer.resizeWorld();
// Set the tiles for collision.
// Do this BEFORE generating the p2 bodies below.
map.setCollisionBetween(1, 12);
// Convert the tilemap layer into bodies. Only tiles that collide (see above) are created.
// This call returns an array of body objects which you can perform addition actions on if
// required. There is also a parameter to control optimising the map build.
game.physics.p2.convertTilemap(map, layer);
game.physics.p2.setBoundsToWorld(true, true, true, true, false);
// finally we create the player placing "hero" instance at x=32, y=416
player = game.add.sprite(100, 400, "hero");
game.physics.p2.enable(player);
// this is the gravity applied to the player
player.body.gravity.y = 12;
player.anchor.setTo(0.5, 0.5);
stars = game.add.sprite(2480, 400, "star");
// the fastest way to create game controls is "createCursorKeys" method
// which automatically assigns up, down, left and right movement to
// arrow keys
cursors = game.input.keyboard.createCursorKeys();
player.checkWorldBounds = true;
player.events.onOutOfBounds.add(playerOut, this);
game.camera.follow(player);
function playerOut(player) {
// Move the player to the start
player.reset(100, 400);
}
},
update: function () {
// we are looking for collisions between the hero and the tiles
game.physics.collide(player, layer);
game.physics.overlap(player, stars,...