pymunk_demo_platformer_06.py Full Listing

pymunk_demo_platformer_06.py
  1"""
  2Example of Pymunk Physics Engine Platformer
  3"""
  4
  5import arcade
  6
  7SCREEN_TITLE = "PyMunk Platformer"
  8
  9# How big are our image tiles?
 10SPRITE_IMAGE_SIZE = 128
 11
 12# Scale sprites up or down
 13SPRITE_SCALING_PLAYER = 0.5
 14SPRITE_SCALING_TILES = 0.5
 15
 16# Scaled sprite size for tiles
 17SPRITE_SIZE = int(SPRITE_IMAGE_SIZE * SPRITE_SCALING_PLAYER)
 18
 19# Size of grid to show on screen, in number of tiles
 20SCREEN_GRID_WIDTH = 25
 21SCREEN_GRID_HEIGHT = 15
 22
 23# Size of screen to show, in pixels
 24SCREEN_WIDTH = SPRITE_SIZE * SCREEN_GRID_WIDTH
 25SCREEN_HEIGHT = SPRITE_SIZE * SCREEN_GRID_HEIGHT
 26
 27# --- Physics forces. Higher number, faster accelerating.
 28
 29# Gravity
 30GRAVITY = 1500
 31
 32# Damping - Amount of speed lost per second
 33DEFAULT_DAMPING = 1.0
 34PLAYER_DAMPING = 0.4
 35
 36# Friction between objects
 37PLAYER_FRICTION = 1.0
 38WALL_FRICTION = 0.7
 39DYNAMIC_ITEM_FRICTION = 0.6
 40
 41# Mass (defaults to 1)
 42PLAYER_MASS = 2.0
 43
 44# Keep player from going too fast
 45PLAYER_MAX_HORIZONTAL_SPEED = 450
 46PLAYER_MAX_VERTICAL_SPEED = 1600
 47
 48# Force applied while on the ground
 49PLAYER_MOVE_FORCE_ON_GROUND = 8000
 50
 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: arcade.Sprite | None = None
 63
 64        # Sprite lists we need
 65        self.player_list: arcade.SpriteList | None = None
 66        self.wall_list: arcade.SpriteList | None = None
 67        self.bullet_list: arcade.SpriteList | None = None
 68        self.item_list: arcade.SpriteList | None = 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: arcade.PymunkPhysicsEngine | None = None
 76
 77        # Set background color
 78        self.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        # Map name
 88        map_name = ":resources:/tiled_maps/pymunk_test_map.json"
 89
 90        # Load in TileMap
 91        tile_map = arcade.load_tilemap(map_name, SPRITE_SCALING_TILES)
 92
 93        # Pull the sprite layers out of the tile map
 94        self.wall_list = tile_map.sprite_lists["Platforms"]
 95        self.item_list = tile_map.sprite_lists["Dynamic Items"]
 96
 97        # Create player sprite
 98        self.player_sprite = arcade.Sprite(
 99            ":resources:images/animated_characters/female_person/femalePerson_idle.png",
100            SPRITE_SCALING_PLAYER,
101        )
102        # Set player location
103        grid_x = 1
104        grid_y = 1
105        self.player_sprite.center_x = SPRITE_SIZE * grid_x + SPRITE_SIZE / 2
106        self.player_sprite.center_y = SPRITE_SIZE * grid_y + SPRITE_SIZE / 2
107        # Add to player sprite list
108        self.player_list.append(self.player_sprite)
109
110        # --- Pymunk Physics Engine Setup ---
111
112        # The default damping for every object controls the percent of velocity
113        # the object will keep each second. A value of 1.0 is no speed loss,
114        # 0.9 is 10% per second, 0.1 is 90% per second.
115        # For top-down games, this is basically the friction for moving objects.
116        # For platformers with gravity, this should probably be set to 1.0.
117        # Default value is 1.0 if not specified.
118        damping = DEFAULT_DAMPING
119
120        # Set the gravity. (0, 0) is good for outer space and top-down.
121        gravity = (0, -GRAVITY)
122
123        # Create the physics engine
124        self.physics_engine = arcade.PymunkPhysicsEngine(damping=damping, gravity=gravity)
125
126        # Add the player.
127        # For the player, we set the damping to a lower value, which increases
128        # the damping rate. This prevents the character from traveling too far
129        # after the player lets off the movement keys.
130        # Setting the moment of inertia to PymunkPhysicsEngine.MOMENT_INF prevents it from
131        # rotating.
132        # Friction normally goes between 0 (no friction) and 1.0 (high friction)
133        # Friction is between two objects in contact. It is important to remember
134        # in top-down games that friction moving along the 'floor' is controlled
135        # by damping.
136        self.physics_engine.add_sprite(
137            self.player_sprite,
138            friction=PLAYER_FRICTION,
139            mass=PLAYER_MASS,
140            moment_of_inertia=arcade.PymunkPhysicsEngine.MOMENT_INF,
141            collision_type="player",
142            max_horizontal_velocity=PLAYER_MAX_HORIZONTAL_SPEED,
143            max_vertical_velocity=PLAYER_MAX_VERTICAL_SPEED,
144        )
145
146        # Create the walls.
147        # By setting the body type to PymunkPhysicsEngine.STATIC the walls can't
148        # move.
149        # Movable objects that respond to forces are PymunkPhysicsEngine.DYNAMIC
150        # PymunkPhysicsEngine.KINEMATIC objects will move, but are assumed to be
151        # repositioned by code and don't respond to physics forces.
152        # Dynamic is default.
153        self.physics_engine.add_sprite_list(
154            self.wall_list,
155            friction=WALL_FRICTION,
156            collision_type="wall",
157            body_type=arcade.PymunkPhysicsEngine.STATIC,
158        )
159
160        # Create the items
161        self.physics_engine.add_sprite_list(
162            self.item_list, friction=DYNAMIC_ITEM_FRICTION, collision_type="item"
163        )
164
165    def on_key_press(self, key, modifiers):
166        """Called whenever a key is pressed."""
167
168        if key == arcade.key.LEFT:
169            self.left_pressed = True
170        elif key == arcade.key.RIGHT:
171            self.right_pressed = True
172
173    def on_key_release(self, key, modifiers):
174        """Called when the user releases a key."""
175
176        if key == arcade.key.LEFT:
177            self.left_pressed = False
178        elif key == arcade.key.RIGHT:
179            self.right_pressed = False
180
181    def on_update(self, delta_time):
182        """Movement and game logic"""
183
184        # Update player forces based on keys pressed
185        if self.left_pressed and not self.right_pressed:
186            # Create a force to the left. Apply it.
187            force = (-PLAYER_MOVE_FORCE_ON_GROUND, 0)
188            self.physics_engine.apply_force(self.player_sprite, force)
189            # Set friction to zero for the player while moving
190            self.physics_engine.set_friction(self.player_sprite, 0)
191        elif self.right_pressed and not self.left_pressed:
192            # Create a force to the right. Apply it.
193            force = (PLAYER_MOVE_FORCE_ON_GROUND, 0)
194            self.physics_engine.apply_force(self.player_sprite, force)
195            # Set friction to zero for the player while moving
196            self.physics_engine.set_friction(self.player_sprite, 0)
197        else:
198            # Player's feet are not moving. Therefore up the friction so we stop.
199            self.physics_engine.set_friction(self.player_sprite, 1.0)
200
201        # Move items in the physics engine
202        self.physics_engine.step()
203
204    def on_draw(self):
205        """Draw everything"""
206        self.clear()
207        self.wall_list.draw()
208        self.bullet_list.draw()
209        self.item_list.draw()
210        self.player_list.draw()
211
212
213def main():
214    """Main function"""
215    window = GameWindow(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
216    window.setup()
217    arcade.run()
218
219
220if __name__ == "__main__":
221    main()