- Getting Started with melon.js
- Recipe: Creating a Tiled Map
- Recipe: Starting the Game
- Recipe: Adding a Character
- Recipe: Building a Collision Map
- Recipe: Walking and Jumping
- Recipe: Title Screen
- Recipe: Adding Collectables
- Recipe: Enemies
- Recipe: Powerups
- Recipe: Losing, Winning, and Information
- Summary
Recipe: Walking and Jumping
To enable walking and jumping, we’ll have to make two changes. First, we’ll want to bind the jump, left, and right buttons to keys on the keyboard. If we alter the screens.js file so that we can do that, we will arrive at something like the code in Listing 5.9.
Listing 5.9. Binding Keys to Move
var PlayScreen = me.ScreenObject.extend({ onResetEvent: function() { me.levelDirector.loadLevel("level1"); me.input.bindKey(me.input.KEY.LEFT, "left"); me.input.bindKey(me.input.KEY.RIGHT, "right"); me.input.bindKey(me.input.KEY.SPACE, "jump"); } });
Then, the init and update functions of the PlayerEntity must be altered in your entities.js file. In your init function, you need to set the default walking and jumping speed, and in the update function, you need to handle updating the movement based on input, as well as checking for collisions. The code needed for these tasks is in Listing 5.10.
Listing 5.10. Handling Player Movement
init: function(x, y, settings) { this.parent(x, y, settings); me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH); this.setVelocity(3, 12); }, update: function() { if (me.input.isKeyPressed('left')) { this.doWalk(true); } else if (me.input.isKeyPressed('right')) { this.doWalk(false); } else { this.vel.x = 0; }; if (me.input.isKeyPressed('jump')) { this.doJump(); } me.game.collide(this); this.updateMovement(); if (this.vel.x!=0 || this.vel.y!=0) { this.parent(this); return true; } return false; }
melonJS comes with these handy convenience functions of doJump() and doWalk(), which are useful for getting started. Keep in mind that hand-crafting acceleration envelopes, although more challenging, can provide a different character for a game. Sonic the Hedgehog is a notable example, owing much of its popularity to the unique slow acceleration and high maximum velocity of the title character. In fact, there is even an HTML5 game engine created entirely to explore his movement in a three-dimensional space.
If you load the index.html file, you may notice that the arrow keys and spacebar can now be used to control Guy! You’re well on your way. You may have also noticed that Guy’s feet move when he walks. melonJS did that for you. All you had to do was load the player.png spritesheet with two sprites, and it knew what you wanted. Fantastic!
What’s next? Despite your best efforts, Guy will occasionally fall in a hole. Then, you should expect the player to refresh the browser every time, right? Nope. Let’s reset the game when things go awry.