Skip to content

Instantly share code, notes, and snippets.

@topherPedersen
Created July 31, 2019 20:45
Show Gist options
  • Save topherPedersen/f91608be9ebb9b9531cde488c9161b26 to your computer and use it in GitHub Desktop.
Save topherPedersen/f91608be9ebb9b9531cde488c9161b26 to your computer and use it in GitHub Desktop.
SpaceWalk PhaserJS Tutorial
<!DOCTYPE html>
<html>
<head>
<script src="//cdn.jsdelivr.net/npm/phaser@3.18.0/dist/phaser.js"></script>
<!-- import phaser (phaser.js) -->
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/phaser-ce/2.13.2/phaser.min.js"></script> -->
<style>
body {
margin: 0;
overflow: hidden;
}
</style>
</head>
<body>
<script>
var config = {
type: Phaser.AUTO,
width: window.outerWidth,
height: window.innerHeight,
physics: {
default: 'arcade',
arcade: {
/* gravity: { y: 300 }, */
debug: false
}
},
scene: {
preload: preload,
create: create,
update: update
}
};
// DECLARE GLOBAL VARIABLES
var spaceMan;
var game = new Phaser.Game(config);
function preload() {
// do stuff
this.load.image('space', 'assets/high-res-space.jpg');
// LOAD SPRITE
this.load.image('spaceMan', 'assets/spaceMan.png');
}
function create() {
// do stuff
this.add.image(window.outerWidth / 2, window.innerHeight / 2, 'space');
spaceMan = this.physics.add.sprite(window.outerWidth / 2, window.innerHeight / 2, 'spaceMan');
spaceMan.angle = 270;
// ADD CURSORS (USER INPUT / CONTROLS)
cursors = this.input.keyboard.createCursorKeys();
// SET SPACEMAN VELOCITY
spaceMan.body.velocity.x = 0;
spaceMan.body.velocity.y = 0;
spaceMan.body.angularVelocity = 0;
spaceMan.body.velocityFromAngle = 0;
spaceMan.setDamping(true);
spaceMan.setDrag(0.99);
spaceMan.setMaxVelocity(200);
}
var coordinatesDisplayed = false;
var centerX;
var centerY;
function update() {
// ROTATIONAL THRUST
if (cursors.left.isDown) {
spaceMan.angle -= 0.5;
} else if (cursors.right.isDown) {
spaceMan.angle += 0.5;
}
// FORWARD THRUST
if (cursors.up.isDown) {
this.physics.velocityFromRotation(spaceMan.rotation, 200, spaceMan.body.acceleration);
// DOWNWARD THRUST
} else if (cursors.down.isDown) {
this.physics.velocityFromRotation(spaceMan.rotation, -200, spaceMan.body.acceleration);
} else {
spaceMan.setAcceleration(0);
}
this.physics.world.wrap(spaceMan, 250);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment