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