pymunk_demo_platformer_10.py Full Listing#

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