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