pymunk_demo_platformer_11.py Full Listing#

pymunk_demo_platformer_11.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# How much force to put on the bullet
 69BULLET_MOVE_FORCE = 4500
 70
 71# Mass of the bullet
 72BULLET_MASS = 0.1
 73
 74# Make bullet less affected by gravity
 75BULLET_GRAVITY = 300
 76
 77
 78class PlayerSprite(arcade.Sprite):
 79    """ Player Sprite """
 80    def __init__(self):
 81        """ Init """
 82        # Let parent initialize
 83        super().__init__()
 84
 85        # Set our scale
 86        self.scale = SPRITE_SCALING_PLAYER
 87
 88        # Images from Kenney.nl's Character pack
 89        # main_path = ":resources:images/animated_characters/female_adventurer/femaleAdventurer"
 90        main_path = ":resources:images/animated_characters/female_person/femalePerson"
 91        # main_path = ":resources:images/animated_characters/male_person/malePerson"
 92        # main_path = ":resources:images/animated_characters/male_adventurer/maleAdventurer"
 93        # main_path = ":resources:images/animated_characters/zombie/zombie"
 94        # main_path = ":resources:images/animated_characters/robot/robot"
 95
 96        # Load textures for idle standing
 97        self.idle_texture_pair = arcade.load_texture_pair(f"{main_path}_idle.png")
 98        self.jump_texture_pair = arcade.load_texture_pair(f"{main_path}_jump.png")
 99        self.fall_texture_pair = arcade.load_texture_pair(f"{main_path}_fall.png")
100
101        # Load textures for walking
102        self.walk_textures = []
103        for i in range(8):
104            texture = arcade.load_texture_pair(f"{main_path}_walk{i}.png")
105            self.walk_textures.append(texture)
106
107        # Set the initial texture
108        self.texture = self.idle_texture_pair[0]
109
110        # Hit box will be set based on the first image used.
111        self.hit_box = self.texture.hit_box_points
112
113        # Default to face-right
114        self.character_face_direction = RIGHT_FACING
115
116        # Index of our current texture
117        self.cur_texture = 0
118
119        # How far have we traveled horizontally since changing the texture
120        self.x_odometer = 0
121
122    def pymunk_moved(self, physics_engine, dx, dy, d_angle):
123        """ Handle being moved by the pymunk engine """
124        # Figure out if we need to face left or right
125        if dx < -DEAD_ZONE and self.character_face_direction == RIGHT_FACING:
126            self.character_face_direction = LEFT_FACING
127        elif dx > DEAD_ZONE and self.character_face_direction == LEFT_FACING:
128            self.character_face_direction = RIGHT_FACING
129
130        # Are we on the ground?
131        is_on_ground = physics_engine.is_on_ground(self)
132
133        # Add to the odometer how far we've moved
134        self.x_odometer += dx
135
136        # Jumping animation
137        if not is_on_ground:
138            if dy > DEAD_ZONE:
139                self.texture = self.jump_texture_pair[self.character_face_direction]
140                return
141            elif dy < -DEAD_ZONE:
142                self.texture = self.fall_texture_pair[self.character_face_direction]
143                return
144
145        # Idle animation
146        if abs(dx) <= DEAD_ZONE:
147            self.texture = self.idle_texture_pair[self.character_face_direction]
148            return
149
150        # Have we moved far enough to change the texture?
151        if abs(self.x_odometer) > DISTANCE_TO_CHANGE_TEXTURE:
152
153            # Reset the odometer
154            self.x_odometer = 0
155
156            # Advance the walking animation
157            self.cur_texture += 1
158            if self.cur_texture > 7:
159                self.cur_texture = 0
160            self.texture = self.walk_textures[self.cur_texture][self.character_face_direction]
161
162
163class BulletSprite(arcade.SpriteSolidColor):
164    """ Bullet Sprite """
165    def pymunk_moved(self, physics_engine, dx, dy, d_angle):
166        """ Handle when the sprite is moved by the physics engine. """
167        # If the bullet falls below the screen, remove it
168        if self.center_y < -100:
169            self.remove_from_sprite_lists()
170
171
172class GameWindow(arcade.Window):
173    """ Main Window """
174
175    def __init__(self, width, height, title):
176        """ Create the variables """
177
178        # Init the parent class
179        super().__init__(width, height, title)
180
181        # Player sprite
182        self.player_sprite: Optional[PlayerSprite] = None
183
184        # Sprite lists we need
185        self.player_list: Optional[arcade.SpriteList] = None
186        self.wall_list: Optional[arcade.SpriteList] = None
187        self.bullet_list: Optional[arcade.SpriteList] = None
188        self.item_list: Optional[arcade.SpriteList] = None
189        self.moving_sprites_list: Optional[arcade.SpriteList] = None
190
191        # Track the current state of what key is pressed
192        self.left_pressed: bool = False
193        self.right_pressed: bool = False
194
195        # Physics engine
196        self.physics_engine = Optional[arcade.PymunkPhysicsEngine]
197
198        # Set background color
199        arcade.set_background_color(arcade.color.AMAZON)
200
201    def setup(self):
202        """ Set up everything with the game """
203
204        # Create the sprite lists
205        self.player_list = arcade.SpriteList()
206        self.bullet_list = arcade.SpriteList()
207
208        # Map name
209        map_name = ":resources:/tiled_maps/pymunk_test_map.json"
210
211        # Load in TileMap
212        tile_map = arcade.load_tilemap(map_name, SPRITE_SCALING_TILES)
213
214        # Pull the sprite layers out of the tile map
215        self.wall_list = tile_map.sprite_lists["Platforms"]
216        self.item_list = tile_map.sprite_lists["Dynamic Items"]
217
218        # Create player sprite
219        self.player_sprite = PlayerSprite()
220
221        # Set player location
222        grid_x = 1
223        grid_y = 1
224        self.player_sprite.center_x = SPRITE_SIZE * grid_x + SPRITE_SIZE / 2
225        self.player_sprite.center_y = SPRITE_SIZE * grid_y + SPRITE_SIZE / 2
226        # Add to player sprite list
227        self.player_list.append(self.player_sprite)
228
229        # Moving Sprite
230        self.moving_sprites_list = arcade.tilemap.process_layer(my_map,
231                                                                'Moving Platforms',
232                                                                SPRITE_SCALING_TILES)
233
234        # --- Pymunk Physics Engine Setup ---
235
236        # The default damping for every object controls the percent of velocity
237        # the object will keep each second. A value of 1.0 is no speed loss,
238        # 0.9 is 10% per second, 0.1 is 90% per second.
239        # For top-down games, this is basically the friction for moving objects.
240        # For platformers with gravity, this should probably be set to 1.0.
241        # Default value is 1.0 if not specified.
242        damping = DEFAULT_DAMPING
243
244        # Set the gravity. (0, 0) is good for outer space and top-down.
245        gravity = (0, -GRAVITY)
246
247        # Create the physics engine
248        self.physics_engine = arcade.PymunkPhysicsEngine(damping=damping,
249                                                         gravity=gravity)
250
251        def wall_hit_handler(bullet_sprite, _wall_sprite, _arbiter, _space, _data):
252            """ Called for bullet/wall collision """
253            bullet_sprite.remove_from_sprite_lists()
254
255        self.physics_engine.add_collision_handler("bullet", "wall", post_handler=wall_hit_handler)
256
257        def item_hit_handler(bullet_sprite, item_sprite, _arbiter, _space, _data):
258            """ Called for bullet/wall collision """
259            bullet_sprite.remove_from_sprite_lists()
260            item_sprite.remove_from_sprite_lists()
261
262        self.physics_engine.add_collision_handler("bullet", "item", post_handler=item_hit_handler)
263
264        # Add the player.
265        # For the player, we set the damping to a lower value, which increases
266        # the damping rate. This prevents the character from traveling too far
267        # after the player lets off the movement keys.
268        # Setting the moment to PymunkPhysicsEngine.MOMENT_INF prevents it from
269        # rotating.
270        # Friction normally goes between 0 (no friction) and 1.0 (high friction)
271        # Friction is between two objects in contact. It is important to remember
272        # in top-down games that friction moving along the 'floor' is controlled
273        # by damping.
274        self.physics_engine.add_sprite(self.player_sprite,
275                                       friction=PLAYER_FRICTION,
276                                       mass=PLAYER_MASS,
277                                       moment=arcade.PymunkPhysicsEngine.MOMENT_INF,
278                                       collision_type="player",
279                                       max_horizontal_velocity=PLAYER_MAX_HORIZONTAL_SPEED,
280                                       max_vertical_velocity=PLAYER_MAX_VERTICAL_SPEED)
281
282        # Create the walls.
283        # By setting the body type to PymunkPhysicsEngine.STATIC the walls can't
284        # move.
285        # Movable objects that respond to forces are PymunkPhysicsEngine.DYNAMIC
286        # PymunkPhysicsEngine.KINEMATIC objects will move, but are assumed to be
287        # repositioned by code and don't respond to physics forces.
288        # Dynamic is default.
289        self.physics_engine.add_sprite_list(self.wall_list,
290                                            friction=WALL_FRICTION,
291                                            collision_type="wall",
292                                            body_type=arcade.PymunkPhysicsEngine.STATIC)
293
294        # Create the items
295        self.physics_engine.add_sprite_list(self.item_list,
296                                            friction=DYNAMIC_ITEM_FRICTION,
297                                            collision_type="item")
298
299        # Add kinematic sprites
300        self.physics_engine.add_sprite_list(self.moving_sprites_list,
301                                            body_type=arcade.PymunkPhysicsEngine.KINEMATIC)
302
303    def on_key_press(self, key, modifiers):
304        """Called whenever a key is pressed. """
305
306        if key == arcade.key.LEFT:
307            self.left_pressed = True
308        elif key == arcade.key.RIGHT:
309            self.right_pressed = True
310        elif key == arcade.key.UP:
311            # find out if player is standing on ground
312            if self.physics_engine.is_on_ground(self.player_sprite):
313                # She is! Go ahead and jump
314                impulse = (0, PLAYER_JUMP_IMPULSE)
315                self.physics_engine.apply_impulse(self.player_sprite, impulse)
316
317    def on_key_release(self, key, modifiers):
318        """Called when the user releases a key. """
319
320        if key == arcade.key.LEFT:
321            self.left_pressed = False
322        elif key == arcade.key.RIGHT:
323            self.right_pressed = False
324
325    def on_mouse_press(self, x, y, button, modifiers):
326        """ Called whenever the mouse button is clicked. """
327
328        bullet = BulletSprite(20, 5, arcade.color.DARK_YELLOW)
329        self.bullet_list.append(bullet)
330
331        # Position the bullet at the player's current location
332        start_x = self.player_sprite.center_x
333        start_y = self.player_sprite.center_y
334        bullet.position = self.player_sprite.position
335
336        # Get from the mouse the destination location for the bullet
337        # IMPORTANT! If you have a scrolling screen, you will also need
338        # to add in self.view_bottom and self.view_left.
339        dest_x = x
340        dest_y = y
341
342        # Do math to calculate how to get the bullet to the destination.
343        # Calculation the angle in radians between the start points
344        # and end points. This is the angle the bullet will travel.
345        x_diff = dest_x - start_x
346        y_diff = dest_y - start_y
347        angle = math.atan2(y_diff, x_diff)
348
349        # What is the 1/2 size of this sprite, so we can figure out how far
350        # away to spawn the bullet
351        size = max(self.player_sprite.width, self.player_sprite.height) / 2
352
353        # Use angle to to spawn bullet away from player in proper direction
354        bullet.center_x += size * math.cos(angle)
355        bullet.center_y += size * math.sin(angle)
356
357        # Set angle of bullet
358        bullet.angle = math.degrees(angle)
359
360        # Gravity to use for the bullet
361        # If we don't use custom gravity, bullet drops too fast, or we have
362        # to make it go too fast.
363        # Force is in relation to bullet's angle.
364        bullet_gravity = (0, -BULLET_GRAVITY)
365
366        # Add the sprite. This needs to be done AFTER setting the fields above.
367        self.physics_engine.add_sprite(bullet,
368                                       mass=BULLET_MASS,
369                                       damping=1.0,
370                                       friction=0.6,
371                                       collision_type="bullet",
372                                       gravity=bullet_gravity,
373                                       elasticity=0.9)
374
375        # Add force to bullet
376        force = (BULLET_MOVE_FORCE, 0)
377        self.physics_engine.apply_force(bullet, force)
378
379    def on_update(self, delta_time):
380        """ Movement and game logic """
381
382        is_on_ground = self.physics_engine.is_on_ground(self.player_sprite)
383        # Update player forces based on keys pressed
384        if self.left_pressed and not self.right_pressed:
385            # Create a force to the left. Apply it.
386            if is_on_ground:
387                force = (-PLAYER_MOVE_FORCE_ON_GROUND, 0)
388            else:
389                force = (-PLAYER_MOVE_FORCE_IN_AIR, 0)
390            self.physics_engine.apply_force(self.player_sprite, force)
391            # Set friction to zero for the player while moving
392            self.physics_engine.set_friction(self.player_sprite, 0)
393        elif self.right_pressed and not self.left_pressed:
394            # Create a force to the right. Apply it.
395            if is_on_ground:
396                force = (PLAYER_MOVE_FORCE_ON_GROUND, 0)
397            else:
398                force = (PLAYER_MOVE_FORCE_IN_AIR, 0)
399            self.physics_engine.apply_force(self.player_sprite, force)
400            # Set friction to zero for the player while moving
401            self.physics_engine.set_friction(self.player_sprite, 0)
402        else:
403            # Player's feet are not moving. Therefore up the friction so we stop.
404            self.physics_engine.set_friction(self.player_sprite, 1.0)
405
406        # Move items in the physics engine
407        self.physics_engine.step()
408
409        # For each moving sprite, see if we've reached a boundary and need to
410        # reverse course.
411        for moving_sprite in self.moving_sprites_list:
412            if moving_sprite.boundary_right and \
413                    moving_sprite.change_x > 0 and \
414                    moving_sprite.right > moving_sprite.boundary_right:
415                moving_sprite.change_x *= -1
416            elif moving_sprite.boundary_left and \
417                    moving_sprite.change_x < 0 and \
418                    moving_sprite.left > moving_sprite.boundary_left:
419                moving_sprite.change_x *= -1
420            if moving_sprite.boundary_top and \
421                    moving_sprite.change_y > 0 and \
422                    moving_sprite.top > moving_sprite.boundary_top:
423                moving_sprite.change_y *= -1
424            elif moving_sprite.boundary_bottom and \
425                    moving_sprite.change_y < 0 and \
426                    moving_sprite.bottom < moving_sprite.boundary_bottom:
427                moving_sprite.change_y *= -1
428
429            # Figure out and set our moving platform velocity.
430            # Pymunk uses velocity is in pixels per second. If we instead have
431            # pixels per frame, we need to convert.
432            velocity = (moving_sprite.change_x * 1 / delta_time, moving_sprite.change_y * 1 / delta_time)
433            self.physics_engine.set_velocity(moving_sprite, velocity)
434
435    def on_draw(self):
436        """ Draw everything """
437        self.clear()
438        self.wall_list.draw()
439        self.moving_sprites_list.draw()
440        self.bullet_list.draw()
441        self.item_list.draw()
442        self.player_list.draw()
443
444def main():
445    """ Main function """
446    window = GameWindow(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
447    window.setup()
448    arcade.run()
449
450
451if __name__ == "__main__":
452    main()