Now our hero is jumping. But there is a problem. Sometimes the jump just doesn’t happen and even when it does, it feels a bit funny.<\/p>\n
After some testing what I found out was that the listeners were sometimes being called in the wrong order. If I clicked fast it would trigger the up event before the down event and it would immediately wipe out the power. I fixed this by doing 3 things<\/p>\n
See the highlighted\u00a0lines below:<\/p>\n
var StateMain = {\r\n preload: function() {\r\n game.load.image(\"ground\", \"images\/ground.png\");\r\n game.load.image(\"hero\", \"images\/hero.png\");\r\n game.load.image(\"bar\", \"images\/powerbar.png\");\r\n game.load.image(\"block\", \"images\/block.png\");\r\n },\r\n create: function() {\r\n this.power = 0;\r\n \/\/turn the background sky blue\r\n game.stage.backgroundColor = \"#00ffff\";\r\n \/\/add the ground\r\n this.ground = game.add.sprite(0, game.height * .9, \"ground\");\r\n \/\/add the hero in \r\n this.hero = game.add.sprite(game.width * .2, this.ground.y - 25, \"hero\");\r\n \/\/add the power bar just above the head of the hero\r\n this.powerBar = game.add.sprite(this.hero.x + 25, this.hero.y - 25, \"bar\");\r\n this.powerBar.width = 0;\r\n \/\/start the physics engine\r\n game.physics.startSystem(Phaser.Physics.ARCADE);\r\n \/\/enable the hero for physics\r\n game.physics.enable(this.hero, Phaser.Physics.ARCADE);\r\n game.physics.enable(this.ground, Phaser.Physics.ARCADE);\r\n \/\/game.physics.arcade.gravity.y = 100;\r\n this.hero.body.gravity.y = 200;\r\n this.hero.body.collideWorldBounds = true;\r\n this.hero.body.bounce.set(0, .2);\r\n this.ground.body.immovable = true;\r\n \/\/set listeners\r\n game.input.onDown.add(this.mouseDown, this);\r\n },\r\n mouseDown: function() {\r\n game.input.onDown.remove(this.mouseDown, this);\r\n this.timer = game.time.events.loop(Phaser.Timer.SECOND \/ 1000, this.increasePower, this);\r\n game.input.onUp.add(this.mouseUp, this);\r\n },\r\n mouseUp: function() {\r\n game.input.onUp.remove(this.mouseUp, this);\r\n this.doJump();\r\n game.time.events.remove(this.timer);\r\n this.power = 0;\r\n this.powerBar.width = 0;\r\n game.input.onDown.add(this.mouseDown, this);\r\n },\r\n increasePower: function() {\r\n this.power++;\r\n this.powerBar.width = this.power;\r\n if (this.power > 50) {\r\n this.power = 50;\r\n }\r\n },\r\n doJump: function() {\r\n this.hero.body.velocity.y = -this.power * 12;\r\n },\r\n update: function() {\r\n game.physics.arcade.collide(this.hero, this.ground);\r\n }\r\n}<\/pre>\n\n\n