JSFiddle - React, Tailwind, and code Playground
by Vincent Roumier
HTML
<script src="http://vincent-roumier.fr/public/phaser.min.js"></script>
JavaScript
var game = new Phaser.Game(300, 300, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update });
function preload() {
game.stage.backgroundColor = '#fff4d9';
game.load.image('atari', 'assets/sprites/atari130xe.png');
}
var sprite;
var platform;
var cursors;
function create() {
// Enable p2 physics
game.physics.startSystem(Phaser.Physics.P2JS);
game.physics.p2.gravity.y = 600;
// Add a sprite
sprite = game.add.sprite(200, 200, 'atari');
game.physics.p2.enable(sprite);
sprite.body.data.mass = 1;
sprite.body.fixedRotation = true;
sprite.groundVelo = new Phaser.Point();
// Add a platform
platform = game.add.sprite(40, 250, 'atari');
platform.width = 100;
game.physics.p2.enable(platform);
platform.body.fixedRotation = true;
platform.body.data.gravityScale = 0;
platform.body.kinematic = true;
platform.body.data.mass = 1000000;
//On contact; keep reference to the current ground velocity
sprite.body.onBeginContact.add(function(_otherBody){if(_otherBody)sprite.groundVelo = _otherBody.velocity}, this);
//on end contact, loose reference
sprite.body.onEndContact.add(function(_otherBody){if(_otherBody)sprite.groundVelo = new Phaser.Point();}, this);
cursors = game.input.keyboard.createCursorKeys();
cursors.up.onDown.add(jump,this);
}
function update() {
//make the platform move
updatePlatform();
if (cursors.left.isDown)
{
//move left, considering ground velocity
sprite.body.velocity.x = -80 + ( sprite.groundVelo.x >0 ? 0 : sprite.groundVelo.x) ;
}
else if (cursors.right.isDown)
{
//move right
sprite.body.velocity.x = 80 + ( sprite.groundVelo.x <0 ? 0 : sprite.groundVelo.x);
}else{
//idle
sprite.body.velocity.x = sprite.groundVelo.x;
}
}
function updatePlatform(){
if(platform.x > 200)
platform.body.velocity.x = -100;
if(platform.x <=...