Step 4 - Add User Control#

Now we need to be able to get the user to move around.

First, at the top of the program add a constant that controls how many pixels per update our character travels:

04_user_control.py - Player Move Speed Constant#
TILE_SCALING = 0.5

Next, at the end of our setup method, we need to create a physics engine that will move our player and keep her from running through walls. The PhysicsEngineSimple class takes two parameters: The moving sprite, and a list of sprites the moving sprite can’t move through.

For more information about the physics engine we are using in this tutorial, see arcade.PhysicsEngineSimple.

Note

It is possible to have multiple physics engines, one per moving sprite. These are very simple, but easy physics engines. See Pymunk Platformer for a more advanced physics engine.

04_user_control.py - Create Physics Engine#
            self.scene.add_sprite("Walls", wall)

        # Create the 'physics engine'
        self.physics_engine = arcade.PhysicsEngineSimple(

Each sprite has center_x and center_y attributes. Changing these will change the location of the sprite. (There are also attributes for top, bottom, left, right, and angle that will move the sprite.)

Each sprite has change_x and change_y variables. These can be used to hold the velocity that the sprite is moving with. We will adjust these based on what key the user hits. If the user hits the right arrow key we want a positive value for change_x. If the value is 5, it will move 5 pixels per frame.

In this case, when the user presses a key we’ll change the sprites change x and y. The physics engine will look at that, and move the player unless she’ll hit a wall.

04_user_control.py - Handle key-down#
 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            self.player_sprite.change_y = PLAYER_MOVEMENT_SPEED
 6        elif key == arcade.key.DOWN or key == arcade.key.S:
 7            self.player_sprite.change_y = -PLAYER_MOVEMENT_SPEED
 8        elif key == arcade.key.LEFT or key == arcade.key.A:
 9            self.player_sprite.change_x = -PLAYER_MOVEMENT_SPEED
10        elif key == arcade.key.RIGHT or key == arcade.key.D:
11            self.player_sprite.change_x = PLAYER_MOVEMENT_SPEED

On releasing the key, we’ll put our speed back to zero.

04_user_control.py - Handle key-up#
 1    def on_key_release(self, key, modifiers):
 2        """Called when the user releases a key."""
 3
 4        if key == arcade.key.UP or key == arcade.key.W:
 5            self.player_sprite.change_y = 0
 6        elif key == arcade.key.DOWN or key == arcade.key.S:
 7            self.player_sprite.change_y = 0
 8        elif key == arcade.key.LEFT or key == arcade.key.A:
 9            self.player_sprite.change_x = 0
10        elif key == arcade.key.RIGHT or key == arcade.key.D:
11            self.player_sprite.change_x = 0

Note

This method of tracking the speed to the key the player presses is simple, but isn’t perfect. If the player hits both left and right keys at the same time, then lets off the left one, we expect the player to move right. This method won’t support that. If you want a slightly more complex method that does, see Better Move By Keyboard.

Our on_update method is called about 60 times per second. We’ll ask the physics engine to move our player based on her change_x and change_y.

04_user_control.py - Update the sprites#
1    def on_update(self, delta_time):
2        """Movement and game logic"""
3
4        # Move the player with the physics engine
5        self.physics_engine.update()

Source Code#

04_user_control.py - User Control#
  1"""
  2Platformer Game
  3
  4python -m arcade.examples.platform_tutorial.04_user_control
  5"""
  6import arcade
  7
  8# Constants
  9SCREEN_WIDTH = 1000
 10SCREEN_HEIGHT = 650
 11SCREEN_TITLE = "Platformer"
 12
 13# Constants used to scale our sprites from their original size
 14CHARACTER_SCALING = 1
 15TILE_SCALING = 0.5
 16
 17# Movement speed of player, in pixels per frame
 18PLAYER_MOVEMENT_SPEED = 5
 19
 20
 21class MyGame(arcade.Window):
 22    """
 23    Main application class.
 24    """
 25
 26    def __init__(self):
 27
 28        # Call the parent class and set up the window
 29        super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
 30
 31        # Our Scene Object
 32        self.scene = None
 33
 34        # Separate variable that holds the player sprite
 35        self.player_sprite = None
 36
 37        # Our physics engine
 38        self.physics_engine = None
 39
 40        arcade.set_background_color(arcade.csscolor.CORNFLOWER_BLUE)
 41
 42    def setup(self):
 43        """Set up the game here. Call this function to restart the game."""
 44
 45        # Initialize Scene
 46        self.scene = arcade.Scene()
 47
 48        # Set up the player, specifically placing it at these coordinates.
 49        image_source = ":resources:images/animated_characters/female_adventurer/femaleAdventurer_idle.png"
 50        self.player_sprite = arcade.Sprite(image_source, CHARACTER_SCALING)
 51        self.player_sprite.center_x = 64
 52        self.player_sprite.center_y = 128
 53        self.scene.add_sprite("Player", self.player_sprite)
 54
 55        # Create the ground
 56        # This shows using a loop to place multiple sprites horizontally
 57        for x in range(0, 1250, 64):
 58            wall = arcade.Sprite(":resources:images/tiles/grassMid.png", TILE_SCALING)
 59            wall.center_x = x
 60            wall.center_y = 32
 61            self.scene.add_sprite("Walls", wall)
 62
 63        # Put some crates on the ground
 64        # This shows using a coordinate list to place sprites
 65        coordinate_list = [[512, 96], [256, 96], [768, 96]]
 66
 67        for coordinate in coordinate_list:
 68            # Add a crate on the ground
 69            wall = arcade.Sprite(
 70                ":resources:images/tiles/boxCrate_double.png", TILE_SCALING
 71            )
 72            wall.position = coordinate
 73            self.scene.add_sprite("Walls", wall)
 74
 75        # Create the 'physics engine'
 76        self.physics_engine = arcade.PhysicsEngineSimple(
 77            self.player_sprite, self.scene.get_sprite_list("Walls")
 78        )
 79
 80    def on_draw(self):
 81        """Render the screen."""
 82
 83        # Clear the screen to the background color
 84        self.clear()
 85
 86        # Draw our Scene
 87        self.scene.draw()
 88
 89    def on_key_press(self, key, modifiers):
 90        """Called whenever a key is pressed."""
 91
 92        if key == arcade.key.UP or key == arcade.key.W:
 93            self.player_sprite.change_y = PLAYER_MOVEMENT_SPEED
 94        elif key == arcade.key.DOWN or key == arcade.key.S:
 95            self.player_sprite.change_y = -PLAYER_MOVEMENT_SPEED
 96        elif key == arcade.key.LEFT or key == arcade.key.A:
 97            self.player_sprite.change_x = -PLAYER_MOVEMENT_SPEED
 98        elif key == arcade.key.RIGHT or key == arcade.key.D:
 99            self.player_sprite.change_x = PLAYER_MOVEMENT_SPEED
100
101    def on_key_release(self, key, modifiers):
102        """Called when the user releases a key."""
103
104        if key == arcade.key.UP or key == arcade.key.W:
105            self.player_sprite.change_y = 0
106        elif key == arcade.key.DOWN or key == arcade.key.S:
107            self.player_sprite.change_y = 0
108        elif key == arcade.key.LEFT or key == arcade.key.A:
109            self.player_sprite.change_x = 0
110        elif key == arcade.key.RIGHT or key == arcade.key.D:
111            self.player_sprite.change_x = 0
112
113    def on_update(self, delta_time):
114        """Movement and game logic"""
115
116        # Move the player with the physics engine
117        self.physics_engine.update()
118
119
120def main():
121    """Main function"""
122    window = MyGame()
123    window.setup()
124    arcade.run()
125
126
127if __name__ == "__main__":
128    main()