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