Character Controls
Learn to add keyboard controls in PhaserJS to move and animate your game character with ease.
In the last chapter, we learned how to make our game world gravity-licious with some solid physics and collision detection! 🛠 Now it's time to help our character break free from standing still—he’s been stuck for too long! He’s probably thinking, "Hey, I've been standing here forever! Do something before I collapse!" So let's give him some controls before he faints from boredom! 😴
PhaserJS makes it super easy to handle keyboard events. We’ll use the built-in keyboard controls feature to move our character left, right, and make him jump around! 🏃♂️💨
Adding Keyboard Controls 🕹️
To get started, add the following line inside the create()
function in your mainScene.js
file:
What’s happening here? 🧠
This magical line creates an object this.cursors
, which gives you access to the arrow keys: up ⬆️, down ⬇️, left ⬅️, and right ➡️. With these, we can detect when the player is pressing any of those keys! 🎉
Moving the Character 🏃♂️
Now, let’s get the character moving! Add the following code inside the update()
function:
Breaking it Down 🧩
-
Left and Right Movement:
- When the left arrow key is pressed,
this.cursors.left.isDown
becomes true. We set the character’s horizontal velocity to-200
to move left. Similarly, pressing the right arrow key sets the velocity to200
for moving right. - We also flip the character's sprite (
flipX = true
orfalse
) to make him face the correct direction. 🔄 - If the player is on the ground (
this.player.body.touching.down
), we trigger the running animation. 🏃♂️
- When the left arrow key is pressed,
-
Stopping the Character:
- If neither the left nor right key is pressed, the velocity is set to
0
so the player doesn’t keep moving. We also switch back to the idle animation if the player is still on the ground. 🛑
- If neither the left nor right key is pressed, the velocity is set to
-
Jumping:
- When the up arrow key is pressed and the player is on the ground, we set the vertical velocity to
-370
, making the character jump. 🚀 - While jumping, we switch to the jump animation. 🦘
- When the up arrow key is pressed and the player is on the ground, we set the vertical velocity to
You Did It! 🎉
Whoa, you did it! Your character now runs left and right, and even jumps like a pro. 🎮 Adding controls wasn’t that hard, right? Now you can run around your game world and have some fun. 🏃♂️💥
In the next chapter, we’ll spice things up by adding apple collection 🍎 and other fun features! Stay tuned for more adventure!
Complete Code 📜
If you missed anything or made some accidental changes, here’s the complete code for reference! 💻🔧
Now you have everything! 🚀 Enjoy creating your awesome PhaserJS game!