Part 2: The Bird
We are going to fill in the preload(), create() and update() functions, and add some new functions to make the game work.
Let's first focus on adding a bird to the game that can be controlled with the spacebar key.
Everything is quite simple and well commented, so you should be able to understand easily the code below.
Everything is quite simple and well commented, so you should be able to understand easily the code below.
First we update the preload(), create() and update() functions.
preload: function() {
// Change the background color of the game game.stage.backgroundColor = '#71c5cf'; // Load the bird sprite game.load.image('bird', 'assets/bird.png'); }, create: function() { // Set the physics system game.physics.startSystem(Phaser.Physics.ARCADE); // Display the bird on the screen this.bird = this.game.add.sprite(100, 245, 'bird'); // Add gravity to the bird to make it fall game.physics.arcade.enable(this.bird); this.bird.body.gravity.y = 1000; // Call the 'jump' function when the spacekey is hit var spaceKey = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); spaceKey.onDown.add(this.jump, this); }, update: function() { // If the bird is out of the world (too high or too low), call the 'restartGame' function if (this.bird.inWorld == false) this.restartGame(); }, |
And just below this, we add these two new functions:
// Make the bird jump
jump: function() { // Add a vertical velocity to the bird this.bird.body.velocity.y = -350; }, // Restart the game restartGame: function() { // Start the 'main' state, which restarts the game game.state.start('main'); }, |