Step 4 - Add Gravity¶
The example above works great for top-down, but what if it is a side view with jumping? We need to add gravity. First, let’s define a constant to represent the acceleration for gravity, and one for a jump speed.
GRAVITY = 1
PLAYER_JUMP_SPEED = 20
At the end of the setup
method, change the physics engine to
PhysicsEnginePlatformer
and include gravity as a parameter.
# Create the 'physics engine'
self.physics_engine = arcade.PhysicsEnginePlatformer(self.player_sprite,
self.wall_list,
GRAVITY)
Then, modify the key down and key up event handlers. We’ll remove the up/down statements we had before, and make ‘UP’ jump when pressed.
1 def on_key_press(self, key, modifiers):
2 """Called whenever a key is pressed. """
3
4 if key == arcade.key.UP or key == arcade.key.W:
5 if self.physics_engine.can_jump():
6 self.player_sprite.change_y = PLAYER_JUMP_SPEED
7 elif key == arcade.key.LEFT or key == arcade.key.A:
8 self.player_sprite.change_x = -PLAYER_MOVEMENT_SPEED
9 elif key == arcade.key.RIGHT or key == arcade.key.D:
10 self.player_sprite.change_x = PLAYER_MOVEMENT_SPEED
11
12 def on_key_release(self, key, modifiers):
13 """Called when the user releases a key. """
14
15 if key == arcade.key.LEFT or key == arcade.key.A:
16 self.player_sprite.change_x = 0
17 elif key == arcade.key.RIGHT or key == arcade.key.D:
18 self.player_sprite.change_x = 0
Note
You can change how the user jumps by changing the gravity and jump constants. Lower values for both will make for a more “floaty” character. Higher values make for a faster-paced game.