pymunk_demo_platformer_08.py Full Listing#

pymunk_demo_platformer_08.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
 58# Close enough to not-moving to have the animation go to idle.
 59DEAD_ZONE = 0.1
 60
 61# Constants used to track if the player is facing left or right
 62RIGHT_FACING = 0
 63LEFT_FACING = 1
 64
 65# How many pixels to move before we change the texture in the walking animation
 66DISTANCE_TO_CHANGE_TEXTURE = 20
 67
 68
 69class PlayerSprite(arcade.Sprite):
 70    """ Player Sprite """
 71    def __init__(self):
 72        """ Init """
 73        # Let parent initialize
 74        super().__init__()
 75
 76        # Set our scale
 77        self.scale = SPRITE_SCALING_PLAYER
 78
 79        # Images from Kenney.nl's Character pack
 80        # main_path = ":resources:images/animated_characters/female_adventurer/femaleAdventurer"
 81        main_path = ":resources:images/animated_characters/female_person/femalePerson"
 82        # main_path = ":resources:images/animated_characters/male_person/malePerson"
 83        # main_path = ":resources:images/animated_characters/male_adventurer/maleAdventurer"
 84        # main_path = ":resources:images/animated_characters/zombie/zombie"
 85        # main_path = ":resources:images/animated_characters/robot/robot"
 86
 87        # Load textures for idle standing
 88        self.idle_texture_pair = arcade.load_texture_pair(f"{main_path}_idle.png")
 89        self.jump_texture_pair = arcade.load_texture_pair(f"{main_path}_jump.png")
 90        self.fall_texture_pair = arcade.load_texture_pair(f"{main_path}_fall.png")
 91
 92        # Load textures for walking
 93        self.walk_textures = []
 94        for i in range(8):
 95            texture = arcade.load_texture_pair(f"{main_path}_walk{i}.png")
 96            self.walk_textures.append(texture)
 97
 98        # Set the initial texture
 99        self.texture = self.idle_texture_pair[0]
100
101        # Hit box will be set based on the first image used.
102        self.hit_box = self.texture.hit_box_points
103
104        # Default to face-right
105        self.character_face_direction = RIGHT_FACING
106
107        # Index of our current texture
108        self.cur_texture = 0
109
110        # How far have we traveled horizontally since changing the texture
111        self.x_odometer = 0
112
113    def pymunk_moved(self, physics_engine, dx, dy, d_angle):
114        """ Handle being moved by the pymunk engine """
115        # Figure out if we need to face left or right
116        if dx < -DEAD_ZONE and self.character_face_direction == RIGHT_FACING:
117            self.character_face_direction = LEFT_FACING
118        elif dx > DEAD_ZONE and self.character_face_direction == LEFT_FACING:
119            self.character_face_direction = RIGHT_FACING
120
121        # Are we on the ground?
122        is_on_ground = physics_engine.is_on_ground(self)
123
124        # Add to the odometer how far we've moved
125        self.x_odometer += dx
126
127        # Jumping animation
128        if not is_on_ground:
129            if dy > DEAD_ZONE:
130                self.texture = self.jump_texture_pair[self.character_face_direction]
131                return
132            elif dy < -DEAD_ZONE:
133                self.texture = self.fall_texture_pair[self.character_face_direction]
134                return
135
136        # Idle animation
137        if abs(dx) <= DEAD_ZONE:
138            self.texture = self.idle_texture_pair[self.character_face_direction]
139            return
140
141        # Have we moved far enough to change the texture?
142        if abs(self.x_odometer) > DISTANCE_TO_CHANGE_TEXTURE:
143
144            # Reset the odometer
145            self.x_odometer = 0
146
147            # Advance the walking animation
148            self.cur_texture += 1
149            if self.cur_texture > 7:
150                self.cur_texture = 0
151            self.texture = self.walk_textures[self.cur_texture][self.character_face_direction]
152
153
154class GameWindow(arcade.Window):
155    """ Main Window """
156
157    def __init__(self, width, height, title):
158        """ Create the variables """
159
160        # Init the parent class
161        super().__init__(width, height, title)
162
163        # Player sprite
164        self.player_sprite: Optional[PlayerSprite] = None
165
166        # Sprite lists we need
167        self.player_list: Optional[arcade.SpriteList] = None
168        self.wall_list: Optional[arcade.SpriteList] = None
169        self.bullet_list: Optional[arcade.SpriteList] = None
170        self.item_list: Optional[arcade.SpriteList] = None
171
172        # Track the current state of what key is pressed
173        self.left_pressed: bool = False
174        self.right_pressed: bool = False
175
176        # Physics engine
177        self.physics_engine = Optional[arcade.PymunkPhysicsEngine]
178
179        # Set background color
180        arcade.set_background_color(arcade.color.AMAZON)
181
182    def setup(self):
183        """ Set up everything with the game """
184
185        # Create the sprite lists
186        self.player_list = arcade.SpriteList()
187        self.bullet_list = arcade.SpriteList()
188
189        # Map name
190        map_name = ":resources:/tiled_maps/pymunk_test_map.json"
191
192        # Load in TileMap
193        tile_map = arcade.load_tilemap(map_name, SPRITE_SCALING_TILES)
194
195        # Pull the sprite layers out of the tile map
196        self.wall_list = tile_map.sprite_lists["Platforms"]
197        self.item_list = tile_map.sprite_lists["Dynamic Items"]
198
199        # Create player sprite
200        self.player_sprite = PlayerSprite()
201
202        # Set player location
203        grid_x = 1
204        grid_y = 1
205        self.player_sprite.center_x = SPRITE_SIZE * grid_x + SPRITE_SIZE / 2
206        self.player_sprite.center_y = SPRITE_SIZE * grid_y + SPRITE_SIZE / 2
207        # Add to player sprite list
208        self.player_list.append(self.player_sprite)
209
210        # --- Pymunk Physics Engine Setup ---
211
212        # The default damping for every object controls the percent of velocity
213        # the object will keep each second. A value of 1.0 is no speed loss,
214        # 0.9 is 10% per second, 0.1 is 90% per second.
215        # For top-down games, this is basically the friction for moving objects.
216        # For platformers with gravity, this should probably be set to 1.0.
217        # Default value is 1.0 if not specified.
218        damping = DEFAULT_DAMPING
219
220        # Set the gravity. (0, 0) is good for outer space and top-down.
221        gravity = (0, -GRAVITY)
222
223        # Create the physics engine
224        self.physics_engine = arcade.PymunkPhysicsEngine(damping=damping,
225                                                         gravity=gravity)
226
227        # Add the player.
228        # For the player, we set the damping to a lower value, which increases
229        # the damping rate. This prevents the character from traveling too far
230        # after the player lets off the movement keys.
231        # Setting the moment to PymunkPhysicsEngine.MOMENT_INF prevents it from
232        # rotating.
233        # Friction normally goes between 0 (no friction) and 1.0 (high friction)
234        # Friction is between two objects in contact. It is important to remember
235        # in top-down games that friction moving along the 'floor' is controlled
236        # by damping.
237        self.physics_engine.add_sprite(self.player_sprite,
238                                       friction=PLAYER_FRICTION,
239                                       mass=PLAYER_MASS,
240                                       moment=arcade.PymunkPhysicsEngine.MOMENT_INF,
241                                       collision_type="player",
242                                       max_horizontal_velocity=PLAYER_MAX_HORIZONTAL_SPEED,
243                                       max_vertical_velocity=PLAYER_MAX_VERTICAL_SPEED)
244
245        # Create the walls.
246        # By setting the body type to PymunkPhysicsEngine.STATIC the walls can't
247        # move.
248        # Movable objects that respond to forces are PymunkPhysicsEngine.DYNAMIC
249        # PymunkPhysicsEngine.KINEMATIC objects will move, but are assumed to be
250        # repositioned by code and don't respond to physics forces.
251        # Dynamic is default.
252        self.physics_engine.add_sprite_list(self.wall_list,
253                                            friction=WALL_FRICTION,
254                                            collision_type="wall",
255                                            body_type=arcade.PymunkPhysicsEngine.STATIC)
256
257        # Create the items
258        self.physics_engine.add_sprite_list(self.item_list,
259                                            friction=DYNAMIC_ITEM_FRICTION,
260                                            collision_type="item")
261
262    def on_key_press(self, key, modifiers):
263        """Called whenever a key is pressed. """
264
265        if key == arcade.key.LEFT:
266            self.left_pressed = True
267        elif key == arcade.key.RIGHT:
268            self.right_pressed = True
269        elif key == arcade.key.UP:
270            # find out if player is standing on ground
271            if self.physics_engine.is_on_ground(self.player_sprite):
272                # She is! Go ahead and jump
273                impulse = (0, PLAYER_JUMP_IMPULSE)
274                self.physics_engine.apply_impulse(self.player_sprite, impulse)
275
276    def on_key_release(self, key, modifiers):
277        """Called when the user releases a key. """
278
279        if key == arcade.key.LEFT:
280            self.left_pressed = False
281        elif key == arcade.key.RIGHT:
282            self.right_pressed = False
283
284    def on_update(self, delta_time):
285        """ Movement and game logic """
286
287        is_on_ground = self.physics_engine.is_on_ground(self.player_sprite)
288        # Update player forces based on keys pressed
289        if self.left_pressed and not self.right_pressed:
290            # Create a force to the left. Apply it.
291            if is_on_ground:
292                force = (-PLAYER_MOVE_FORCE_ON_GROUND, 0)
293            else:
294                force = (-PLAYER_MOVE_FORCE_IN_AIR, 0)
295            self.physics_engine.apply_force(self.player_sprite, force)
296            # Set friction to zero for the player while moving
297            self.physics_engine.set_friction(self.player_sprite, 0)
298        elif self.right_pressed and not self.left_pressed:
299            # Create a force to the right. Apply it.
300            if is_on_ground:
301                force = (PLAYER_MOVE_FORCE_ON_GROUND, 0)
302            else:
303                force = (PLAYER_MOVE_FORCE_IN_AIR, 0)
304            self.physics_engine.apply_force(self.player_sprite, force)
305            # Set friction to zero for the player while moving
306            self.physics_engine.set_friction(self.player_sprite, 0)
307        else:
308            # Player's feet are not moving. Therefore up the friction so we stop.
309            self.physics_engine.set_friction(self.player_sprite, 1.0)
310
311        # Move items in the physics engine
312        self.physics_engine.step()
313
314    def on_draw(self):
315        """ Draw everything """
316        self.clear()
317        self.wall_list.draw()
318        self.bullet_list.draw()
319        self.item_list.draw()
320        self.player_list.draw()
321
322def main():
323    """ Main function """
324    window = GameWindow(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
325    window.setup()
326    arcade.run()
327
328
329if __name__ == "__main__":
330    main()