pymunk_demo_platformer_11.py Full Listing
pymunk_demo_platformer_11.py
1"""
2Example of Pymunk Physics Engine Platformer
3"""
4import math
5from typing import Optional
6
7import arcade
8
9SCREEN_TITLE = "PyMunk Platformer"
10
11# How big are our image tiles?
12SPRITE_IMAGE_SIZE = 128
13
14# Scale sprites up or down
15SPRITE_SCALING_PLAYER = 0.5
16SPRITE_SCALING_TILES = 0.5
17
18# Scaled sprite size for tiles
19SPRITE_SIZE = int(SPRITE_IMAGE_SIZE * SPRITE_SCALING_PLAYER)
20
21# Size of grid to show on screen, in number of tiles
22SCREEN_GRID_WIDTH = 25
23SCREEN_GRID_HEIGHT = 15
24
25# Size of screen to show, in pixels
26SCREEN_WIDTH = SPRITE_SIZE * SCREEN_GRID_WIDTH
27SCREEN_HEIGHT = SPRITE_SIZE * SCREEN_GRID_HEIGHT
28
29# --- Physics forces. Higher number, faster accelerating.
30
31# Gravity
32GRAVITY = 1500
33
34# Damping - Amount of speed lost per second
35DEFAULT_DAMPING = 1.0
36PLAYER_DAMPING = 0.4
37
38# Friction between objects
39PLAYER_FRICTION = 1.0
40WALL_FRICTION = 0.7
41DYNAMIC_ITEM_FRICTION = 0.6
42
43# Mass (defaults to 1)
44PLAYER_MASS = 2.0
45
46# Keep player from going too fast
47PLAYER_MAX_HORIZONTAL_SPEED = 450
48PLAYER_MAX_VERTICAL_SPEED = 1600
49
50# Force applied while on the ground
51PLAYER_MOVE_FORCE_ON_GROUND = 8000
52
53# Force applied when moving left/right in the air
54PLAYER_MOVE_FORCE_IN_AIR = 900
55
56# Strength of a jump
57PLAYER_JUMP_IMPULSE = 1800
58
59# Close enough to not-moving to have the animation go to idle.
60DEAD_ZONE = 0.1
61
62# Constants used to track if the player is facing left or right
63RIGHT_FACING = 0
64LEFT_FACING = 1
65
66# How many pixels to move before we change the texture in the walking animation
67DISTANCE_TO_CHANGE_TEXTURE = 20
68
69# How much force to put on the bullet
70BULLET_MOVE_FORCE = 4500
71
72# Mass of the bullet
73BULLET_MASS = 0.1
74
75# Make bullet less affected by gravity
76BULLET_GRAVITY = 300
77
78
79class PlayerSprite(arcade.Sprite):
80 """ Player Sprite """
81 def __init__(self):
82 """ Init """
83 # Let parent initialize
84 super().__init__(scale=SPRITE_SCALING_PLAYER)
85
86 # Images from Kenney.nl's Character pack
87 # main_path = ":resources:images/animated_characters/female_adventurer/femaleAdventurer"
88 main_path = ":resources:images/animated_characters/female_person/femalePerson"
89 # main_path = ":resources:images/animated_characters/male_person/malePerson"
90 # main_path = ":resources:images/animated_characters/male_adventurer/maleAdventurer"
91 # main_path = ":resources:images/animated_characters/zombie/zombie"
92 # main_path = ":resources:images/animated_characters/robot/robot"
93
94 # Load textures for idle, jump, and fall states
95 idle_texture = arcade.load_texture(f"{main_path}_idle.png")
96 jump_texture = arcade.load_texture(f"{main_path}_jump.png")
97 fall_texture = arcade.load_texture(f"{main_path}_fall.png")
98 # Make pairs of textures facing left and right
99 self.idle_texture_pair = idle_texture, idle_texture.flip_left_right()
100 self.jump_texture_pair = jump_texture, jump_texture.flip_left_right()
101 self.fall_texture_pair = fall_texture, fall_texture.flip_left_right()
102
103 # Load textures for walking and make pairs of textures facing left and right
104 self.walk_textures = []
105 for i in range(8):
106 texture = arcade.load_texture(f"{main_path}_walk{i}.png")
107 self.walk_textures.append((texture, texture.flip_left_right()))
108
109 # Set the initial texture
110 self.texture = self.idle_texture_pair[0]
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
161
162class BulletSprite(arcade.SpriteSolidColor):
163 """ Bullet Sprite """
164 def pymunk_moved(self, physics_engine, dx, dy, d_angle):
165 """ Handle when the sprite is moved by the physics engine. """
166 # If the bullet falls below the screen, remove it
167 if self.center_y < -100:
168 self.remove_from_sprite_lists()
169
170
171class GameWindow(arcade.Window):
172 """ Main Window """
173
174 def __init__(self, width, height, title):
175 """ Create the variables """
176
177 # Init the parent class
178 super().__init__(width, height, title)
179
180 # Player sprite
181 self.player_sprite: PlayerSprite|None = None
182
183 # Sprite lists we need
184 self.player_list: arcade.SpriteList|None = None
185 self.wall_list: arcade.SpriteList|None = None
186 self.bullet_list: arcade.SpriteList|None = None
187 self.item_list: arcade.SpriteList|None = None
188 self.moving_sprites_list: arcade.SpriteList|None = None
189
190 # Track the current state of what key is pressed
191 self.left_pressed: bool = False
192 self.right_pressed: bool = False
193
194 # Physics engine
195 self.physics_engine: arcade.PymunkPhysicsEngine | None = None
196
197 # Set background color
198 self.background_color = arcade.color.AMAZON
199
200 def setup(self):
201 """ Set up everything with the game """
202
203 # Create the sprite lists
204 self.player_list = arcade.SpriteList()
205 self.bullet_list = arcade.SpriteList()
206
207 # Map name
208 map_name = ":resources:/tiled_maps/pymunk_test_map.json"
209
210 # Load in TileMap
211 tile_map = arcade.load_tilemap(map_name, SPRITE_SCALING_TILES)
212
213 # Pull the sprite layers out of the tile map
214 self.wall_list = tile_map.sprite_lists["Platforms"]
215 self.item_list = tile_map.sprite_lists["Dynamic Items"]
216
217 # Create player sprite
218 self.player_sprite = PlayerSprite()
219
220 # Set player location
221 grid_x = 1
222 grid_y = 1
223 self.player_sprite.center_x = SPRITE_SIZE * grid_x + SPRITE_SIZE / 2
224 self.player_sprite.center_y = SPRITE_SIZE * grid_y + SPRITE_SIZE / 2
225 # Add to player sprite list
226 self.player_list.append(self.player_sprite)
227
228 # Moving Sprite
229 self.moving_sprites_list = tile_map.sprite_lists['Moving Platforms']
230
231 # --- Pymunk Physics Engine Setup ---
232
233 # The default damping for every object controls the percent of velocity
234 # the object will keep each second. A value of 1.0 is no speed loss,
235 # 0.9 is 10% per second, 0.1 is 90% per second.
236 # For top-down games, this is basically the friction for moving objects.
237 # For platformers with gravity, this should probably be set to 1.0.
238 # Default value is 1.0 if not specified.
239 damping = DEFAULT_DAMPING
240
241 # Set the gravity. (0, 0) is good for outer space and top-down.
242 gravity = (0, -GRAVITY)
243
244 # Create the physics engine
245 self.physics_engine = arcade.PymunkPhysicsEngine(damping=damping,
246 gravity=gravity)
247
248 def wall_hit_handler(bullet_sprite, _wall_sprite, _arbiter, _space, _data):
249 """ Called for bullet/wall collision """
250 bullet_sprite.remove_from_sprite_lists()
251
252 self.physics_engine.add_collision_handler("bullet", "wall", post_handler=wall_hit_handler)
253
254 def item_hit_handler(bullet_sprite, item_sprite, _arbiter, _space, _data):
255 """ Called for bullet/wall collision """
256 bullet_sprite.remove_from_sprite_lists()
257 item_sprite.remove_from_sprite_lists()
258
259 self.physics_engine.add_collision_handler("bullet", "item", post_handler=item_hit_handler)
260
261 # Add the player.
262 # For the player, we set the damping to a lower value, which increases
263 # the damping rate. This prevents the character from traveling too far
264 # after the player lets off the movement keys.
265 # Setting the moment of inertia to PymunkPhysicsEngine.MOMENT_INF prevents it from
266 # rotating.
267 # Friction normally goes between 0 (no friction) and 1.0 (high friction)
268 # Friction is between two objects in contact. It is important to remember
269 # in top-down games that friction moving along the 'floor' is controlled
270 # by damping.
271 self.physics_engine.add_sprite(self.player_sprite,
272 friction=PLAYER_FRICTION,
273 mass=PLAYER_MASS,
274 moment_of_inertia=arcade.PymunkPhysicsEngine.MOMENT_INF,
275 collision_type="player",
276 max_horizontal_velocity=PLAYER_MAX_HORIZONTAL_SPEED,
277 max_vertical_velocity=PLAYER_MAX_VERTICAL_SPEED)
278
279 # Create the walls.
280 # By setting the body type to PymunkPhysicsEngine.STATIC the walls can't
281 # move.
282 # Movable objects that respond to forces are PymunkPhysicsEngine.DYNAMIC
283 # PymunkPhysicsEngine.KINEMATIC objects will move, but are assumed to be
284 # repositioned by code and don't respond to physics forces.
285 # Dynamic is default.
286 self.physics_engine.add_sprite_list(self.wall_list,
287 friction=WALL_FRICTION,
288 collision_type="wall",
289 body_type=arcade.PymunkPhysicsEngine.STATIC)
290
291 # Create the items
292 self.physics_engine.add_sprite_list(self.item_list,
293 friction=DYNAMIC_ITEM_FRICTION,
294 collision_type="item")
295
296 # Add kinematic sprites
297 self.physics_engine.add_sprite_list(self.moving_sprites_list,
298 body_type=arcade.PymunkPhysicsEngine.KINEMATIC)
299
300 def on_key_press(self, key, modifiers):
301 """Called whenever a key is pressed. """
302
303 if key == arcade.key.LEFT:
304 self.left_pressed = True
305 elif key == arcade.key.RIGHT:
306 self.right_pressed = True
307 elif key == arcade.key.UP:
308 # find out if player is standing on ground
309 if self.physics_engine.is_on_ground(self.player_sprite):
310 # She is! Go ahead and jump
311 impulse = (0, PLAYER_JUMP_IMPULSE)
312 self.physics_engine.apply_impulse(self.player_sprite, impulse)
313
314 def on_key_release(self, key, modifiers):
315 """Called when the user releases a key. """
316
317 if key == arcade.key.LEFT:
318 self.left_pressed = False
319 elif key == arcade.key.RIGHT:
320 self.right_pressed = False
321
322 def on_mouse_press(self, x, y, button, modifiers):
323 """ Called whenever the mouse button is clicked. """
324
325 bullet = BulletSprite(width=20, height=5, color=arcade.color.DARK_YELLOW)
326 self.bullet_list.append(bullet)
327
328 # Position the bullet at the player's current location
329 start_x = self.player_sprite.center_x
330 start_y = self.player_sprite.center_y
331 bullet.position = self.player_sprite.position
332
333 # Get from the mouse the destination location for the bullet
334 # IMPORTANT! If you have a scrolling screen, you will also need
335 # to add in self.view_bottom and self.view_left.
336 dest_x = x
337 dest_y = y
338
339 # Do math to calculate how to get the bullet to the destination.
340 # Calculation the angle in radians between the start points
341 # and end points. This is the angle the bullet will travel.
342 x_diff = dest_x - start_x
343 y_diff = dest_y - start_y
344 angle = math.atan2(y_diff, x_diff)
345
346 # What is the 1/2 size of this sprite, so we can figure out how far
347 # away to spawn the bullet
348 size = max(self.player_sprite.width, self.player_sprite.height) / 2
349
350 # Use angle to to spawn bullet away from player in proper direction
351 bullet.center_x += size * math.cos(angle)
352 bullet.center_y += size * math.sin(angle)
353
354 # Set angle of bullet
355 bullet.angle = math.degrees(angle)
356
357 # Gravity to use for the bullet
358 # If we don't use custom gravity, bullet drops too fast, or we have
359 # to make it go too fast.
360 # Force is in relation to bullet's angle.
361 bullet_gravity = (0, -BULLET_GRAVITY)
362
363 # Add the sprite. This needs to be done AFTER setting the fields above.
364 self.physics_engine.add_sprite(bullet,
365 mass=BULLET_MASS,
366 damping=1.0,
367 friction=0.6,
368 collision_type="bullet",
369 gravity=bullet_gravity,
370 elasticity=0.9)
371
372 # Add force to bullet
373 force = (BULLET_MOVE_FORCE, 0)
374 self.physics_engine.apply_force(bullet, force)
375
376 def on_update(self, delta_time):
377 """ Movement and game logic """
378
379 is_on_ground = self.physics_engine.is_on_ground(self.player_sprite)
380 # Update player forces based on keys pressed
381 if self.left_pressed and not self.right_pressed:
382 # Create a force to the left. Apply it.
383 if is_on_ground:
384 force = (-PLAYER_MOVE_FORCE_ON_GROUND, 0)
385 else:
386 force = (-PLAYER_MOVE_FORCE_IN_AIR, 0)
387 self.physics_engine.apply_force(self.player_sprite, force)
388 # Set friction to zero for the player while moving
389 self.physics_engine.set_friction(self.player_sprite, 0)
390 elif self.right_pressed and not self.left_pressed:
391 # Create a force to the right. Apply it.
392 if is_on_ground:
393 force = (PLAYER_MOVE_FORCE_ON_GROUND, 0)
394 else:
395 force = (PLAYER_MOVE_FORCE_IN_AIR, 0)
396 self.physics_engine.apply_force(self.player_sprite, force)
397 # Set friction to zero for the player while moving
398 self.physics_engine.set_friction(self.player_sprite, 0)
399 else:
400 # Player's feet are not moving. Therefore up the friction so we stop.
401 self.physics_engine.set_friction(self.player_sprite, 1.0)
402
403 # Move items in the physics engine
404 self.physics_engine.step()
405
406 # For each moving sprite, see if we've reached a boundary and need to
407 # reverse course.
408 for moving_sprite in self.moving_sprites_list:
409 if moving_sprite.boundary_right and \
410 moving_sprite.change_x > 0 and \
411 moving_sprite.right > moving_sprite.boundary_right:
412 moving_sprite.change_x *= -1
413 elif moving_sprite.boundary_left and \
414 moving_sprite.change_x < 0 and \
415 moving_sprite.left > moving_sprite.boundary_left:
416 moving_sprite.change_x *= -1
417 if moving_sprite.boundary_top and \
418 moving_sprite.change_y > 0 and \
419 moving_sprite.top > moving_sprite.boundary_top:
420 moving_sprite.change_y *= -1
421 elif moving_sprite.boundary_bottom and \
422 moving_sprite.change_y < 0 and \
423 moving_sprite.bottom < moving_sprite.boundary_bottom:
424 moving_sprite.change_y *= -1
425
426 # Figure out and set our moving platform velocity.
427 # Pymunk uses velocity is in pixels per second. If we instead have
428 # pixels per frame, we need to convert.
429 velocity = (moving_sprite.change_x * 1 / delta_time, moving_sprite.change_y * 1 / delta_time)
430 self.physics_engine.set_velocity(moving_sprite, velocity)
431
432 def on_draw(self):
433 """ Draw everything """
434 self.clear()
435 self.wall_list.draw()
436 self.moving_sprites_list.draw()
437 self.bullet_list.draw()
438 self.item_list.draw()
439 self.player_list.draw()
440
441def main():
442 """ Main function """
443 window = GameWindow(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
444 window.setup()
445 arcade.run()
446
447
448if __name__ == "__main__":
449 main()