pymunk_demo_platformer_07.py Full Listing

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