pymunk_demo_platformer_12.py Diff
pymunk_demo_platformer_12.py
--- /home/docs/checkouts/readthedocs.org/user_builds/arcade-library/checkouts/stable/doc/tutorials/pymunk_platformer/pymunk_demo_platformer_11.py
+++ /home/docs/checkouts/readthedocs.org/user_builds/arcade-library/checkouts/stable/doc/tutorials/pymunk_platformer/pymunk_demo_platformer_12.py
@@ -1,9 +1,9 @@
"""
Example of Pymunk Physics Engine Platformer
"""
+
import math
from typing import Optional
-
import arcade
SCREEN_TITLE = "PyMunk Platformer"
@@ -77,9 +77,12 @@
class PlayerSprite(arcade.Sprite):
- """ Player Sprite """
- def __init__(self):
- """ Init """
+ """Player Sprite"""
+
+ def __init__(
+ self, ladder_list: arcade.SpriteList, hit_box_algorithm: arcade.hitbox.HitBoxAlgorithm
+ ):
+ """Init"""
# Let parent initialize
super().__init__(scale=SPRITE_SCALING_PLAYER)
@@ -91,21 +94,30 @@
# 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]
@@ -117,9 +129,13 @@
# 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 """
+ """Handle being moved by the pymunk engine"""
# Figure out if we need to face left or right
if dx < -DEAD_ZONE and self.character_face_direction == RIGHT_FACING:
self.character_face_direction = LEFT_FACING
@@ -129,8 +145,37 @@
# 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:
@@ -148,7 +193,6 @@
# Have we moved far enough to change the texture?
if abs(self.x_odometer) > DISTANCE_TO_CHANGE_TEXTURE:
-
# Reset the odometer
self.x_odometer = 0
@@ -160,45 +204,49 @@
class BulletSprite(arcade.SpriteSolidColor):
- """ Bullet Sprite """
+ """Bullet Sprite"""
+
def pymunk_moved(self, physics_engine, dx, dy, d_angle):
- """ Handle when the sprite is moved by the physics engine. """
+ """Handle when the sprite is moved by the physics engine."""
# If the bullet falls below the screen, remove it
if self.center_y < -100:
self.remove_from_sprite_lists()
class GameWindow(arcade.Window):
- """ Main Window """
+ """Main Window"""
def __init__(self, width, height, title):
- """ Create the variables """
+ """Create the variables"""
# Init the parent class
super().__init__(width, height, title)
# Player sprite
- self.player_sprite: PlayerSprite|None = None
+ self.player_sprite: PlayerSprite | None = None
# Sprite lists we need
- self.player_list: arcade.SpriteList|None = None
- self.wall_list: arcade.SpriteList|None = None
- self.bullet_list: arcade.SpriteList|None = None
- self.item_list: arcade.SpriteList|None = None
- self.moving_sprites_list: arcade.SpriteList|None = None
+ self.player_list: arcade.SpriteList | None = None
+ self.wall_list: arcade.SpriteList | None = None
+ self.bullet_list: arcade.SpriteList | None = None
+ self.item_list: arcade.SpriteList | None = None
+ self.moving_sprites_list: arcade.SpriteList | None = None
+ self.ladder_list: arcade.SpriteList | None = 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: arcade.PymunkPhysicsEngine | None = None
+ self.physics_engine: Optional[arcade.PymunkPhysicsEngine] = None
# Set background color
self.background_color = arcade.color.AMAZON
def setup(self):
- """ Set up everything with the game """
+ """Set up everything with the game"""
# Create the sprite lists
self.player_list = arcade.SpriteList()
@@ -213,9 +261,13 @@
# 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
@@ -225,9 +277,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
@@ -242,17 +291,16 @@
gravity = (0, -GRAVITY)
# Create the physics engine
- self.physics_engine = arcade.PymunkPhysicsEngine(damping=damping,
- gravity=gravity)
+ self.physics_engine = arcade.PymunkPhysicsEngine(damping=damping, gravity=gravity)
def wall_hit_handler(bullet_sprite, _wall_sprite, _arbiter, _space, _data):
- """ Called for bullet/wall collision """
+ """Called for bullet/wall collision"""
bullet_sprite.remove_from_sprite_lists()
self.physics_engine.add_collision_handler("bullet", "wall", post_handler=wall_hit_handler)
def item_hit_handler(bullet_sprite, item_sprite, _arbiter, _space, _data):
- """ Called for bullet/wall collision """
+ """Called for bullet/wall collision"""
bullet_sprite.remove_from_sprite_lists()
item_sprite.remove_from_sprite_lists()
@@ -262,19 +310,21 @@
# 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
# in top-down games that friction moving along the 'floor' is controlled
# by damping.
- self.physics_engine.add_sprite(self.player_sprite,
- friction=PLAYER_FRICTION,
- mass=PLAYER_MASS,
- moment_of_inertia=arcade.PymunkPhysicsEngine.MOMENT_INF,
- collision_type="player",
- max_horizontal_velocity=PLAYER_MAX_HORIZONTAL_SPEED,
- max_vertical_velocity=PLAYER_MAX_VERTICAL_SPEED)
+ self.physics_engine.add_sprite(
+ self.player_sprite,
+ friction=PLAYER_FRICTION,
+ mass=PLAYER_MASS,
+ moment_of_inertia=arcade.PymunkPhysicsEngine.MOMENT_INF,
+ collision_type="player",
+ max_horizontal_velocity=PLAYER_MAX_HORIZONTAL_SPEED,
+ max_vertical_velocity=PLAYER_MAX_VERTICAL_SPEED,
+ )
# Create the walls.
# By setting the body type to PymunkPhysicsEngine.STATIC the walls can't
@@ -283,44 +333,57 @@
# PymunkPhysicsEngine.KINEMATIC objects will move, but are assumed to be
# repositioned by code and don't respond to physics forces.
# Dynamic is default.
- self.physics_engine.add_sprite_list(self.wall_list,
- friction=WALL_FRICTION,
- collision_type="wall",
- body_type=arcade.PymunkPhysicsEngine.STATIC)
+ self.physics_engine.add_sprite_list(
+ self.wall_list,
+ friction=WALL_FRICTION,
+ collision_type="wall",
+ body_type=arcade.PymunkPhysicsEngine.STATIC,
+ )
# Create the items
- self.physics_engine.add_sprite_list(self.item_list,
- friction=DYNAMIC_ITEM_FRICTION,
- collision_type="item")
+ self.physics_engine.add_sprite_list(
+ self.item_list, friction=DYNAMIC_ITEM_FRICTION, collision_type="item"
+ )
# Add kinematic sprites
- self.physics_engine.add_sprite_list(self.moving_sprites_list,
- body_type=arcade.PymunkPhysicsEngine.KINEMATIC)
+ self.physics_engine.add_sprite_list(
+ self.moving_sprites_list, body_type=arcade.PymunkPhysicsEngine.KINEMATIC
+ )
def on_key_press(self, key, modifiers):
- """Called whenever a key is pressed. """
-
- if key == arcade.key.LEFT:
+ """Called whenever a key is pressed."""
+
+ 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:
+ """Called when the user releases a key."""
+
+ 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. """
+ """Called whenever the mouse button is clicked."""
bullet = BulletSprite(width=20, height=5, color=arcade.color.DARK_YELLOW)
self.bullet_list.append(bullet)
@@ -361,26 +424,28 @@
bullet_gravity = (0, -BULLET_GRAVITY)
# Add the sprite. This needs to be done AFTER setting the fields above.
- self.physics_engine.add_sprite(bullet,
- mass=BULLET_MASS,
- damping=1.0,
- friction=0.6,
- collision_type="bullet",
- gravity=bullet_gravity,
- elasticity=0.9)
+ self.physics_engine.add_sprite(
+ bullet,
+ mass=BULLET_MASS,
+ damping=1.0,
+ friction=0.6,
+ collision_type="bullet",
+ gravity=bullet_gravity,
+ elasticity=0.9,
+ )
# Add force to bullet
force = (BULLET_MOVE_FORCE, 0)
self.physics_engine.apply_force(bullet, force)
def on_update(self, delta_time):
- """ Movement and game logic """
+ """Movement and game logic"""
is_on_ground = self.physics_engine.is_on_ground(self.player_sprite)
# 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)
@@ -389,13 +454,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)
@@ -406,40 +486,58 @@
# For each moving sprite, see if we've reached a boundary and need to
# reverse course.
for moving_sprite in self.moving_sprites_list:
- if moving_sprite.boundary_right and \
- moving_sprite.change_x > 0 and \
- moving_sprite.right > moving_sprite.boundary_right:
+ if (
+ moving_sprite.boundary_right
+ and moving_sprite.change_x > 0
+ and moving_sprite.right > moving_sprite.boundary_right
+ ):
moving_sprite.change_x *= -1
- elif moving_sprite.boundary_left and \
- moving_sprite.change_x < 0 and \
- moving_sprite.left > moving_sprite.boundary_left:
+ elif (
+ moving_sprite.boundary_left
+ and moving_sprite.change_x < 0
+ and moving_sprite.left > moving_sprite.boundary_left
+ ):
moving_sprite.change_x *= -1
- if moving_sprite.boundary_top and \
- moving_sprite.change_y > 0 and \
- moving_sprite.top > moving_sprite.boundary_top:
+ if (
+ moving_sprite.boundary_top
+ and moving_sprite.change_y > 0
+ and moving_sprite.top > moving_sprite.boundary_top
+ ):
moving_sprite.change_y *= -1
- elif moving_sprite.boundary_bottom and \
- moving_sprite.change_y < 0 and \
- moving_sprite.bottom < moving_sprite.boundary_bottom:
+ elif (
+ moving_sprite.boundary_bottom
+ and moving_sprite.change_y < 0
+ and moving_sprite.bottom < moving_sprite.boundary_bottom
+ ):
moving_sprite.change_y *= -1
# Figure out and set our moving platform velocity.
# Pymunk uses velocity is in pixels per second. If we instead have
# pixels per frame, we need to convert.
- velocity = (moving_sprite.change_x * 1 / delta_time, moving_sprite.change_y * 1 / delta_time)
+ velocity = (
+ moving_sprite.change_x * 1 / delta_time,
+ moving_sprite.change_y * 1 / delta_time,
+ )
self.physics_engine.set_velocity(moving_sprite, velocity)
def on_draw(self):
- """ Draw everything """
+ """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 """
+ """Main function"""
window = GameWindow(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
window.setup()
arcade.run()