pymunk_demo_platformer_06.py Full Listing

pymunk_demo_platformer_06.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
 52class GameWindow(arcade.Window):
 53    """ Main Window """
 54
 55    def __init__(self, width, height, title):
 56        """ Create the variables """
 57
 58        # Init the parent class
 59        super().__init__(width, height, title)
 60
 61        # Player sprite
 62        self.player_sprite: Optional[arcade.Sprite] = None
 63
 64        # Sprite lists we need
 65        self.player_list: Optional[arcade.SpriteList] = None
 66        self.wall_list: Optional[arcade.SpriteList] = None
 67        self.bullet_list: Optional[arcade.SpriteList] = None
 68        self.item_list: Optional[arcade.SpriteList] = None
 69
 70        # Track the current state of what key is pressed
 71        self.left_pressed: bool = False
 72        self.right_pressed: bool = False
 73
 74        # Physics engine
 75        self.physics_engine = Optional[arcade.PymunkPhysicsEngine]
 76
 77        # Set background color
 78        arcade.set_background_color(arcade.color.AMAZON)
 79
 80    def setup(self):
 81        """ Set up everything with the game """
 82
 83        # Create the sprite lists
 84        self.player_list = arcade.SpriteList()
 85        self.bullet_list = arcade.SpriteList()
 86
 87        # Read in the tiled map
 88        map_name = "pymunk_test_map.tmx"
 89        my_map = arcade.tilemap.read_tmx(map_name)
 90
 91        # Read in the map layers
 92        self.wall_list = arcade.tilemap.process_layer(my_map, 'Platforms', SPRITE_SCALING_TILES)
 93        self.item_list = arcade.tilemap.process_layer(my_map, 'Dynamic Items', SPRITE_SCALING_TILES)
 94
 95        # Create player sprite
 96        self.player_sprite = arcade.Sprite(":resources:images/animated_characters/female_person/femalePerson_idle.png",
 97                                           SPRITE_SCALING_PLAYER)
 98        # Set player location
 99        grid_x = 1
100        grid_y = 1
101        self.player_sprite.center_x = SPRITE_SIZE * grid_x + SPRITE_SIZE / 2
102        self.player_sprite.center_y = SPRITE_SIZE * grid_y + SPRITE_SIZE / 2
103        # Add to player sprite list
104        self.player_list.append(self.player_sprite)
105
106        # --- Pymunk Physics Engine Setup ---
107
108        # The default damping for every object controls the percent of velocity
109        # the object will keep each second. A value of 1.0 is no speed loss,
110        # 0.9 is 10% per second, 0.1 is 90% per second.
111        # For top-down games, this is basically the friction for moving objects.
112        # For platformers with gravity, this should probably be set to 1.0.
113        # Default value is 1.0 if not specified.
114        damping = DEFAULT_DAMPING
115
116        # Set the gravity. (0, 0) is good for outer space and top-down.
117        gravity = (0, -GRAVITY)
118
119        # Create the physics engine
120        self.physics_engine = arcade.PymunkPhysicsEngine(damping=damping,
121                                                         gravity=gravity)
122
123        # Add the player.
124        # For the player, we set the damping to a lower value, which increases
125        # the damping rate. This prevents the character from traveling too far
126        # after the player lets off the movement keys.
127        # Setting the moment to PymunkPhysicsEngine.MOMENT_INF prevents it from
128        # rotating.
129        # Friction normally goes between 0 (no friction) and 1.0 (high friction)
130        # Friction is between two objects in contact. It is important to remember
131        # in top-down games that friction moving along the 'floor' is controlled
132        # by damping.
133        self.physics_engine.add_sprite(self.player_sprite,
134                                       friction=PLAYER_FRICTION,
135                                       mass=PLAYER_MASS,
136                                       moment=arcade.PymunkPhysicsEngine.MOMENT_INF,
137                                       collision_type="player",
138                                       max_horizontal_velocity=PLAYER_MAX_HORIZONTAL_SPEED,
139                                       max_vertical_velocity=PLAYER_MAX_VERTICAL_SPEED)
140
141        # Create the walls.
142        # By setting the body type to PymunkPhysicsEngine.STATIC the walls can't
143        # move.
144        # Movable objects that respond to forces are PymunkPhysicsEngine.DYNAMIC
145        # PymunkPhysicsEngine.KINEMATIC objects will move, but are assumed to be
146        # repositioned by code and don't respond to physics forces.
147        # Dynamic is default.
148        self.physics_engine.add_sprite_list(self.wall_list,
149                                            friction=WALL_FRICTION,
150                                            collision_type="wall",
151                                            body_type=arcade.PymunkPhysicsEngine.STATIC)
152
153        # Create the items
154        self.physics_engine.add_sprite_list(self.item_list,
155                                            friction=DYNAMIC_ITEM_FRICTION,
156                                            collision_type="item")
157
158    def on_key_press(self, key, modifiers):
159        """Called whenever a key is pressed. """
160
161        if key == arcade.key.LEFT:
162            self.left_pressed = True
163        elif key == arcade.key.RIGHT:
164            self.right_pressed = True
165
166    def on_key_release(self, key, modifiers):
167        """Called when the user releases a key. """
168
169        if key == arcade.key.LEFT:
170            self.left_pressed = False
171        elif key == arcade.key.RIGHT:
172            self.right_pressed = False
173
174    def on_update(self, delta_time):
175        """ Movement and game logic """
176
177        # Update player forces based on keys pressed
178        if self.left_pressed and not self.right_pressed:
179            # Create a force to the left. Apply it.
180            force = (-PLAYER_MOVE_FORCE_ON_GROUND, 0)
181            self.physics_engine.apply_force(self.player_sprite, force)
182            # Set friction to zero for the player while moving
183            self.physics_engine.set_friction(self.player_sprite, 0)
184        elif self.right_pressed and not self.left_pressed:
185            # Create a force to the right. Apply it.
186            force = (PLAYER_MOVE_FORCE_ON_GROUND, 0)
187            self.physics_engine.apply_force(self.player_sprite, force)
188            # Set friction to zero for the player while moving
189            self.physics_engine.set_friction(self.player_sprite, 0)
190        else:
191            # Player's feet are not moving. Therefore up the friction so we stop.
192            self.physics_engine.set_friction(self.player_sprite, 1.0)
193
194        # Move items in the physics engine
195        self.physics_engine.step()
196
197    def on_draw(self):
198        """ Draw everything """
199        arcade.start_render()
200        self.wall_list.draw()
201        self.bullet_list.draw()
202        self.item_list.draw()
203        self.player_list.draw()
204
205def main():
206    """ Main method """
207    window = GameWindow(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
208    window.setup()
209    arcade.run()
210
211
212if __name__ == "__main__":
213    main()