pymunk_demo_platformer_12.py Diff

pymunk_demo_platformer_12.py
--- /home/docs/checkouts/readthedocs.org/user_builds/arcade-library/checkouts/development/doc/tutorials/pymunk_platformer/pymunk_demo_platformer_11.py
+++ /home/docs/checkouts/readthedocs.org/user_builds/arcade-library/checkouts/development/doc/tutorials/pymunk_platformer/pymunk_demo_platformer_12.py
@@ -77,7 +77,9 @@
 
 class PlayerSprite(arcade.Sprite):
     """ Player Sprite """
-    def __init__(self):
+    def __init__(self,
+                 ladder_list: arcade.SpriteList,
+                 hit_box_algorithm: arcade.hitbox.HitBoxAlgorithm):
         """ Init """
         # Let parent initialize
         super().__init__(scale=SPRITE_SCALING_PLAYER)
@@ -90,21 +92,28 @@
         # main_path = ":resources:images/animated_characters/zombie/zombie"
         # main_path = ":resources:images/animated_characters/robot/robot"
 
-        # Load textures for idle, jump, and fall states
-        idle_texture = arcade.load_texture(f"{main_path}_idle.png")
+        idle_texture = arcade.load_texture(f"{main_path}_idle.png", hit_box_algorithm=hit_box_algorithm)
         jump_texture = arcade.load_texture(f"{main_path}_jump.png")
-        fall_texture = arcade.load_texture(f"{main_path}_fall.png") 
-        # Make pairs of textures facing left and right
+        fall_texture = arcade.load_texture(f"{main_path}_fall.png")
+
+        # Load textures for idle standing
         self.idle_texture_pair = idle_texture, idle_texture.flip_left_right()
         self.jump_texture_pair = jump_texture, jump_texture.flip_left_right()
         self.fall_texture_pair = fall_texture, fall_texture.flip_left_right()
 
-        # Load textures for walking and make pairs of textures facing left and right
+        # Load textures for walking
         self.walk_textures = []
         for i in range(8):
             texture = arcade.load_texture(f"{main_path}_walk{i}.png")
             self.walk_textures.append((texture, texture.flip_left_right()))
 
+        # Load textures for climbing
+        self.climbing_textures = []
+        texture = arcade.load_texture(f"{main_path}_climb0.png")
+        self.climbing_textures.append(texture)
+        texture = arcade.load_texture(f"{main_path}_climb1.png")
+        self.climbing_textures.append(texture)
+
         # Set the initial texture
         self.texture = self.idle_texture_pair[0]
 
@@ -116,6 +125,10 @@
 
         # How far have we traveled horizontally since changing the texture
         self.x_odometer = 0
+        self.y_odometer = 0
+
+        self.ladder_list = ladder_list
+        self.is_on_ladder = False
 
     def pymunk_moved(self, physics_engine, dx, dy, d_angle):
         """ Handle being moved by the pymunk engine """
@@ -128,8 +141,38 @@
         # Are we on the ground?
         is_on_ground = physics_engine.is_on_ground(self)
 
+        # Are we on a ladder?
+        if len(arcade.check_for_collision_with_list(self, self.ladder_list)) > 0:
+            if not self.is_on_ladder:
+                self.is_on_ladder = True
+                self.pymunk.gravity = (0, 0)
+                self.pymunk.damping = 0.0001
+                self.pymunk.max_vertical_velocity = PLAYER_MAX_HORIZONTAL_SPEED
+        else:
+            if self.is_on_ladder:
+                self.pymunk.damping = 1.0
+                self.pymunk.max_vertical_velocity = PLAYER_MAX_VERTICAL_SPEED
+                self.is_on_ladder = False
+                self.pymunk.gravity = None
+
         # Add to the odometer how far we've moved
         self.x_odometer += dx
+        self.y_odometer += dy
+
+        if self.is_on_ladder and not is_on_ground:
+            # Have we moved far enough to change the texture?
+            if abs(self.y_odometer) > DISTANCE_TO_CHANGE_TEXTURE:
+
+                # Reset the odometer
+                self.y_odometer = 0
+
+                # Advance the walking animation
+                self.cur_texture += 1
+
+            if self.cur_texture > 1:
+                self.cur_texture = 0
+            self.texture = self.climbing_textures[self.cur_texture]
+            return
 
         # Jumping animation
         if not is_on_ground:
@@ -157,7 +200,6 @@
                 self.cur_texture = 0
             self.texture = self.walk_textures[self.cur_texture][self.character_face_direction]
 
-
 class BulletSprite(arcade.SpriteSolidColor):
     """ Bullet Sprite """
     def pymunk_moved(self, physics_engine, dx, dy, d_angle):
@@ -166,7 +208,6 @@
         if self.center_y < -100:
             self.remove_from_sprite_lists()
 
-
 class GameWindow(arcade.Window):
     """ Main Window """
 
@@ -185,13 +226,16 @@
         self.bullet_list: Optional[arcade.SpriteList] = None
         self.item_list: Optional[arcade.SpriteList] = None
         self.moving_sprites_list: Optional[arcade.SpriteList] = None
+        self.ladder_list: Optional[arcade.SpriteList] = None
 
         # Track the current state of what key is pressed
         self.left_pressed: bool = False
         self.right_pressed: bool = False
+        self.up_pressed: bool = False
+        self.down_pressed: bool = False
 
         # Physics engine
-        self.physics_engine = Optional[arcade.PymunkPhysicsEngine]
+        self.physics_engine: Optional[arcade.PymunkPhysicsEngine] = None
 
         # Set background color
         self.background_color = arcade.color.AMAZON
@@ -212,9 +256,11 @@
         # Pull the sprite layers out of the tile map
         self.wall_list = tile_map.sprite_lists["Platforms"]
         self.item_list = tile_map.sprite_lists["Dynamic Items"]
+        self.ladder_list = tile_map.sprite_lists["Ladders"]
+        self.moving_sprites_list = tile_map.sprite_lists['Moving Platforms']
 
         # Create player sprite
-        self.player_sprite = PlayerSprite()
+        self.player_sprite = PlayerSprite(self.ladder_list, hit_box_algorithm=arcade.hitbox.algo_detailed)
 
         # Set player location
         grid_x = 1
@@ -224,9 +270,6 @@
         # Add to player sprite list
         self.player_list.append(self.player_sprite)
 
-        # Moving Sprite
-        self.moving_sprites_list = tile_map.sprite_lists['Moving Platforms']
-
         # --- Pymunk Physics Engine Setup ---
 
         # The default damping for every object controls the percent of velocity
@@ -261,7 +304,7 @@
         # For the player, we set the damping to a lower value, which increases
         # the damping rate. This prevents the character from traveling too far
         # after the player lets off the movement keys.
-        # Setting the moment of inertia to PymunkPhysicsEngine.MOMENT_INF prevents it from
+        # Setting the moment of intertia to PymunkPhysicsEngine.MOMENT_INF prevents it from
         # rotating.
         # Friction normally goes between 0 (no friction) and 1.0 (high friction)
         # Friction is between two objects in contact. It is important to remember
@@ -299,24 +342,32 @@
     def on_key_press(self, key, modifiers):
         """Called whenever a key is pressed. """
 
-        if key == arcade.key.LEFT:
+        if key in (arcade.key.LEFT, arcade.key.A):
             self.left_pressed = True
-        elif key == arcade.key.RIGHT:
+        elif key in (arcade.key.RIGHT, arcade.key.D):
             self.right_pressed = True
-        elif key == arcade.key.UP:
-            # find out if player is standing on ground
-            if self.physics_engine.is_on_ground(self.player_sprite):
+        elif key in (arcade.key.UP, arcade.key.W):
+            self.up_pressed = True
+            # find out if player is standing on ground, and not on a ladder
+            if self.physics_engine.is_on_ground(self.player_sprite) \
+                    and not self.player_sprite.is_on_ladder:
                 # She is! Go ahead and jump
                 impulse = (0, PLAYER_JUMP_IMPULSE)
                 self.physics_engine.apply_impulse(self.player_sprite, impulse)
+        elif key in (arcade.key.DOWN, arcade.key.S):
+            self.down_pressed = True
 
     def on_key_release(self, key, modifiers):
         """Called when the user releases a key. """
 
-        if key == arcade.key.LEFT:
+        if key in (arcade.key.LEFT, arcade.key.A):
             self.left_pressed = False
-        elif key == arcade.key.RIGHT:
+        elif key in (arcade.key.RIGHT, arcade.key.D):
             self.right_pressed = False
+        elif key in (arcade.key.UP, arcade.key.W):
+            self.up_pressed = False
+        elif key in (arcade.key.DOWN, arcade.key.S):
+            self.down_pressed = False
 
     def on_mouse_press(self, x, y, button, modifiers):
         """ Called whenever the mouse button is clicked. """
@@ -379,7 +430,7 @@
         # Update player forces based on keys pressed
         if self.left_pressed and not self.right_pressed:
             # Create a force to the left. Apply it.
-            if is_on_ground:
+            if is_on_ground or self.player_sprite.is_on_ladder:
                 force = (-PLAYER_MOVE_FORCE_ON_GROUND, 0)
             else:
                 force = (-PLAYER_MOVE_FORCE_IN_AIR, 0)
@@ -388,13 +439,28 @@
             self.physics_engine.set_friction(self.player_sprite, 0)
         elif self.right_pressed and not self.left_pressed:
             # Create a force to the right. Apply it.
-            if is_on_ground:
+            if is_on_ground or self.player_sprite.is_on_ladder:
                 force = (PLAYER_MOVE_FORCE_ON_GROUND, 0)
             else:
                 force = (PLAYER_MOVE_FORCE_IN_AIR, 0)
             self.physics_engine.apply_force(self.player_sprite, force)
             # Set friction to zero for the player while moving
             self.physics_engine.set_friction(self.player_sprite, 0)
+        elif self.up_pressed and not self.down_pressed:
+            # Create a force to the right. Apply it.
+            if self.player_sprite.is_on_ladder:
+                force = (0, PLAYER_MOVE_FORCE_ON_GROUND)
+                self.physics_engine.apply_force(self.player_sprite, force)
+                # Set friction to zero for the player while moving
+                self.physics_engine.set_friction(self.player_sprite, 0)
+        elif self.down_pressed and not self.up_pressed:
+            # Create a force to the right. Apply it.
+            if self.player_sprite.is_on_ladder:
+                force = (0, -PLAYER_MOVE_FORCE_ON_GROUND)
+                self.physics_engine.apply_force(self.player_sprite, force)
+                # Set friction to zero for the player while moving
+                self.physics_engine.set_friction(self.player_sprite, 0)
+
         else:
             # Player's feet are not moving. Therefore up the friction so we stop.
             self.physics_engine.set_friction(self.player_sprite, 1.0)
@@ -432,10 +498,16 @@
         """ Draw everything """
         self.clear()
         self.wall_list.draw()
+        self.ladder_list.draw()
         self.moving_sprites_list.draw()
         self.bullet_list.draw()
         self.item_list.draw()
         self.player_list.draw()
+
+        # for item in self.player_list:
+        #     item.draw_hit_box(arcade.color.RED)
+        # for item in self.item_list:
+        #     item.draw_hit_box(arcade.color.RED)
 
 def main():
     """ Main function """