pymunk_demo_platformer_06.py Full Listing#

pymunk_demo_platformer_06.py#
  1"""
  2Example of Pymunk Physics Engine Platformer
  3"""
  4from typing import Optional
  5import arcade
  6
  7SCREEN_TITLE = "PyMunk Platformer"
  8
  9# How big are our image tiles?
 10SPRITE_IMAGE_SIZE = 128
 11
 12# Scale sprites up or down
 13SPRITE_SCALING_PLAYER = 0.5
 14SPRITE_SCALING_TILES = 0.5
 15
 16# Scaled sprite size for tiles
 17SPRITE_SIZE = int(SPRITE_IMAGE_SIZE * SPRITE_SCALING_PLAYER)
 18
 19# Size of grid to show on screen, in number of tiles
 20SCREEN_GRID_WIDTH = 25
 21SCREEN_GRID_HEIGHT = 15
 22
 23# Size of screen to show, in pixels
 24SCREEN_WIDTH = SPRITE_SIZE * SCREEN_GRID_WIDTH
 25SCREEN_HEIGHT = SPRITE_SIZE * SCREEN_GRID_HEIGHT
 26
 27# --- Physics forces. Higher number, faster accelerating.
 28
 29# Gravity
 30GRAVITY = 1500
 31
 32# Damping - Amount of speed lost per second
 33DEFAULT_DAMPING = 1.0
 34PLAYER_DAMPING = 0.4
 35
 36# Friction between objects
 37PLAYER_FRICTION = 1.0
 38WALL_FRICTION = 0.7
 39DYNAMIC_ITEM_FRICTION = 0.6
 40
 41# Mass (defaults to 1)
 42PLAYER_MASS = 2.0
 43
 44# Keep player from going too fast
 45PLAYER_MAX_HORIZONTAL_SPEED = 450
 46PLAYER_MAX_VERTICAL_SPEED = 1600
 47
 48# Force applied while on the ground
 49PLAYER_MOVE_FORCE_ON_GROUND = 8000
 50
 51class GameWindow(arcade.Window):
 52    """ Main Window """
 53
 54    def __init__(self, width, height, title):
 55        """ Create the variables """
 56
 57        # Init the parent class
 58        super().__init__(width, height, title)
 59
 60        # Player sprite
 61        self.player_sprite: Optional[arcade.Sprite] = None
 62
 63        # Sprite lists we need
 64        self.player_list: Optional[arcade.SpriteList] = None
 65        self.wall_list: Optional[arcade.SpriteList] = None
 66        self.bullet_list: Optional[arcade.SpriteList] = None
 67        self.item_list: Optional[arcade.SpriteList] = None
 68
 69        # Track the current state of what key is pressed
 70        self.left_pressed: bool = False
 71        self.right_pressed: bool = False
 72
 73        # Physics engine
 74        self.physics_engine = Optional[arcade.PymunkPhysicsEngine]
 75
 76        # Set background color
 77        self.background_color = arcade.color.AMAZON
 78
 79    def setup(self):
 80        """ Set up everything with the game """
 81
 82        # Create the sprite lists
 83        self.player_list = arcade.SpriteList()
 84        self.bullet_list = arcade.SpriteList()
 85
 86        # Map name
 87        map_name = ":resources:/tiled_maps/pymunk_test_map.json"
 88
 89        # Load in TileMap
 90        tile_map = arcade.load_tilemap(map_name, SPRITE_SCALING_TILES)
 91
 92        # Pull the sprite layers out of the tile map
 93        self.wall_list = tile_map.sprite_lists["Platforms"]
 94        self.item_list = tile_map.sprite_lists["Dynamic Items"]
 95
 96        # Create player sprite
 97        self.player_sprite = arcade.Sprite(":resources:images/animated_characters/female_person/femalePerson_idle.png",
 98                                           SPRITE_SCALING_PLAYER)
 99        # Set player location
100        grid_x = 1
101        grid_y = 1
102        self.player_sprite.center_x = SPRITE_SIZE * grid_x + SPRITE_SIZE / 2
103        self.player_sprite.center_y = SPRITE_SIZE * grid_y + SPRITE_SIZE / 2
104        # Add to player sprite list
105        self.player_list.append(self.player_sprite)
106
107        # --- Pymunk Physics Engine Setup ---
108
109        # The default damping for every object controls the percent of velocity
110        # the object will keep each second. A value of 1.0 is no speed loss,
111        # 0.9 is 10% per second, 0.1 is 90% per second.
112        # For top-down games, this is basically the friction for moving objects.
113        # For platformers with gravity, this should probably be set to 1.0.
114        # Default value is 1.0 if not specified.
115        damping = DEFAULT_DAMPING
116
117        # Set the gravity. (0, 0) is good for outer space and top-down.
118        gravity = (0, -GRAVITY)
119
120        # Create the physics engine
121        self.physics_engine = arcade.PymunkPhysicsEngine(damping=damping,
122                                                         gravity=gravity)
123
124        # Add the player.
125        # For the player, we set the damping to a lower value, which increases
126        # the damping rate. This prevents the character from traveling too far
127        # after the player lets off the movement keys.
128        # Setting the moment of inertia to PymunkPhysicsEngine.MOMENT_INF prevents it from
129        # rotating.
130        # Friction normally goes between 0 (no friction) and 1.0 (high friction)
131        # Friction is between two objects in contact. It is important to remember
132        # in top-down games that friction moving along the 'floor' is controlled
133        # by damping.
134        self.physics_engine.add_sprite(self.player_sprite,
135                                       friction=PLAYER_FRICTION,
136                                       mass=PLAYER_MASS,
137                                       moment_of_inertia=arcade.PymunkPhysicsEngine.MOMENT_INF,
138                                       collision_type="player",
139                                       max_horizontal_velocity=PLAYER_MAX_HORIZONTAL_SPEED,
140                                       max_vertical_velocity=PLAYER_MAX_VERTICAL_SPEED)
141
142        # Create the walls.
143        # By setting the body type to PymunkPhysicsEngine.STATIC the walls can't
144        # move.
145        # Movable objects that respond to forces are PymunkPhysicsEngine.DYNAMIC
146        # PymunkPhysicsEngine.KINEMATIC objects will move, but are assumed to be
147        # repositioned by code and don't respond to physics forces.
148        # Dynamic is default.
149        self.physics_engine.add_sprite_list(self.wall_list,
150                                            friction=WALL_FRICTION,
151                                            collision_type="wall",
152                                            body_type=arcade.PymunkPhysicsEngine.STATIC)
153
154        # Create the items
155        self.physics_engine.add_sprite_list(self.item_list,
156                                            friction=DYNAMIC_ITEM_FRICTION,
157                                            collision_type="item")
158
159    def on_key_press(self, key, modifiers):
160        """Called whenever a key is pressed. """
161
162        if key == arcade.key.LEFT:
163            self.left_pressed = True
164        elif key == arcade.key.RIGHT:
165            self.right_pressed = True
166
167    def on_key_release(self, key, modifiers):
168        """Called when the user releases a key. """
169
170        if key == arcade.key.LEFT:
171            self.left_pressed = False
172        elif key == arcade.key.RIGHT:
173            self.right_pressed = False
174
175    def on_update(self, delta_time):
176        """ Movement and game logic """
177
178        # Update player forces based on keys pressed
179        if self.left_pressed and not self.right_pressed:
180            # Create a force to the left. Apply it.
181            force = (-PLAYER_MOVE_FORCE_ON_GROUND, 0)
182            self.physics_engine.apply_force(self.player_sprite, force)
183            # Set friction to zero for the player while moving
184            self.physics_engine.set_friction(self.player_sprite, 0)
185        elif self.right_pressed and not self.left_pressed:
186            # Create a force to the right. Apply it.
187            force = (PLAYER_MOVE_FORCE_ON_GROUND, 0)
188            self.physics_engine.apply_force(self.player_sprite, force)
189            # Set friction to zero for the player while moving
190            self.physics_engine.set_friction(self.player_sprite, 0)
191        else:
192            # Player's feet are not moving. Therefore up the friction so we stop.
193            self.physics_engine.set_friction(self.player_sprite, 1.0)
194
195        # Move items in the physics engine
196        self.physics_engine.step()
197
198    def on_draw(self):
199        """ Draw everything """
200        self.clear()
201        self.wall_list.draw()
202        self.bullet_list.draw()
203        self.item_list.draw()
204        self.player_list.draw()
205
206def main():
207    """ Main function """
208    window = GameWindow(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
209    window.setup()
210    arcade.run()
211
212
213if __name__ == "__main__":
214    main()