pymunk_demo_platformer_09.py Full Listing#

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