pymunk_demo_platformer_08.py Full Listing
pymunk_demo_platformer_08.py
1"""
2Example of Pymunk Physics Engine Platformer
3"""
4
5import arcade
6
7SCREEN_TITLE = "PyMunk Platformer"
8
9# How big are our image tiles?
10SPRITE_IMAGE_SIZE = 128
11
12# Scale sprites up or down
13SPRITE_SCALING_PLAYER = 0.5
14SPRITE_SCALING_TILES = 0.5
15
16# Scaled sprite size for tiles
17SPRITE_SIZE = int(SPRITE_IMAGE_SIZE * SPRITE_SCALING_PLAYER)
18
19# Size of grid to show on screen, in number of tiles
20SCREEN_GRID_WIDTH = 25
21SCREEN_GRID_HEIGHT = 15
22
23# Size of screen to show, in pixels
24SCREEN_WIDTH = SPRITE_SIZE * SCREEN_GRID_WIDTH
25SCREEN_HEIGHT = SPRITE_SIZE * SCREEN_GRID_HEIGHT
26
27# --- Physics forces. Higher number, faster accelerating.
28
29# Gravity
30GRAVITY = 1500
31
32# Damping - Amount of speed lost per second
33DEFAULT_DAMPING = 1.0
34PLAYER_DAMPING = 0.4
35
36# Friction between objects
37PLAYER_FRICTION = 1.0
38WALL_FRICTION = 0.7
39DYNAMIC_ITEM_FRICTION = 0.6
40
41# Mass (defaults to 1)
42PLAYER_MASS = 2.0
43
44# Keep player from going too fast
45PLAYER_MAX_HORIZONTAL_SPEED = 450
46PLAYER_MAX_VERTICAL_SPEED = 1600
47
48# Force applied while on the ground
49PLAYER_MOVE_FORCE_ON_GROUND = 8000
50
51# Force applied when moving left/right in the air
52PLAYER_MOVE_FORCE_IN_AIR = 900
53
54# Strength of a jump
55PLAYER_JUMP_IMPULSE = 1800
56
57# Close enough to not-moving to have the animation go to idle.
58DEAD_ZONE = 0.1
59
60# Constants used to track if the player is facing left or right
61RIGHT_FACING = 0
62LEFT_FACING = 1
63
64# How many pixels to move before we change the texture in the walking animation
65DISTANCE_TO_CHANGE_TEXTURE = 20
66
67
68class PlayerSprite(arcade.Sprite):
69 """Player Sprite"""
70
71 def __init__(self):
72 """Init"""
73 # Let parent initialize
74 super().__init__(scale=SPRITE_SCALING_PLAYER)
75
76 # Images from Kenney.nl's Character pack
77 # main_path = ":resources:images/animated_characters/female_adventurer/femaleAdventurer"
78 main_path = ":resources:images/animated_characters/female_person/femalePerson"
79 # main_path = ":resources:images/animated_characters/male_person/malePerson"
80 # main_path = ":resources:images/animated_characters/male_adventurer/maleAdventurer"
81 # main_path = ":resources:images/animated_characters/zombie/zombie"
82 # main_path = ":resources:images/animated_characters/robot/robot"
83
84 # Load textures for idle, jump, and fall states
85 idle_texture = arcade.load_texture(f"{main_path}_idle.png")
86 jump_texture = arcade.load_texture(f"{main_path}_jump.png")
87 fall_texture = arcade.load_texture(f"{main_path}_fall.png")
88 # Make pairs of textures facing left and right
89 self.idle_texture_pair = idle_texture, idle_texture.flip_left_right()
90 self.jump_texture_pair = jump_texture, jump_texture.flip_left_right()
91 self.fall_texture_pair = fall_texture, fall_texture.flip_left_right()
92
93 # Load textures for walking and make pairs of textures facing left and right
94 self.walk_textures = []
95 for i in range(8):
96 texture = arcade.load_texture(f"{main_path}_walk{i}.png")
97 self.walk_textures.append((texture, texture.flip_left_right()))
98
99 # Set the initial texture
100 self.texture = self.idle_texture_pair[0]
101
102 # Default to face-right
103 self.character_face_direction = RIGHT_FACING
104
105 # Index of our current texture
106 self.cur_texture = 0
107
108 # How far have we traveled horizontally since changing the texture
109 self.x_odometer = 0
110
111 def pymunk_moved(self, physics_engine, dx, dy, d_angle):
112 """Handle being moved by the pymunk engine"""
113 # Figure out if we need to face left or right
114 if dx < -DEAD_ZONE and self.character_face_direction == RIGHT_FACING:
115 self.character_face_direction = LEFT_FACING
116 elif dx > DEAD_ZONE and self.character_face_direction == LEFT_FACING:
117 self.character_face_direction = RIGHT_FACING
118
119 # Are we on the ground?
120 is_on_ground = physics_engine.is_on_ground(self)
121
122 # Add to the odometer how far we've moved
123 self.x_odometer += dx
124
125 # Jumping animation
126 if not is_on_ground:
127 if dy > DEAD_ZONE:
128 self.texture = self.jump_texture_pair[self.character_face_direction]
129 return
130 elif dy < -DEAD_ZONE:
131 self.texture = self.fall_texture_pair[self.character_face_direction]
132 return
133
134 # Idle animation
135 if abs(dx) <= DEAD_ZONE:
136 self.texture = self.idle_texture_pair[self.character_face_direction]
137 return
138
139 # Have we moved far enough to change the texture?
140 if abs(self.x_odometer) > DISTANCE_TO_CHANGE_TEXTURE:
141 # Reset the odometer
142 self.x_odometer = 0
143
144 # Advance the walking animation
145 self.cur_texture += 1
146 if self.cur_texture > 7:
147 self.cur_texture = 0
148 self.texture = self.walk_textures[self.cur_texture][self.character_face_direction]
149
150
151class GameWindow(arcade.Window):
152 """Main Window"""
153
154 def __init__(self, width, height, title):
155 """Create the variables"""
156
157 # Init the parent class
158 super().__init__(width, height, title)
159
160 # Player sprite
161 self.player_sprite: PlayerSprite | None = None
162
163 # Sprite lists we need
164 self.player_list: arcade.SpriteList | None = None
165 self.wall_list: arcade.SpriteList | None = None
166 self.bullet_list: arcade.SpriteList | None = None
167 self.item_list: arcade.SpriteList | None = None
168
169 # Track the current state of what key is pressed
170 self.left_pressed: bool = False
171 self.right_pressed: bool = False
172
173 # Physics engine
174 self.physics_engine: arcade.PymunkPhysicsEngine | None = None
175
176 # Set background color
177 self.background_color = arcade.color.AMAZON
178
179 def setup(self):
180 """Set up everything with the game"""
181
182 # Create the sprite lists
183 self.player_list = arcade.SpriteList()
184 self.bullet_list = arcade.SpriteList()
185
186 # Map name
187 map_name = ":resources:/tiled_maps/pymunk_test_map.json"
188
189 # Load in TileMap
190 tile_map = arcade.load_tilemap(map_name, SPRITE_SCALING_TILES)
191
192 # Pull the sprite layers out of the tile map
193 self.wall_list = tile_map.sprite_lists["Platforms"]
194 self.item_list = tile_map.sprite_lists["Dynamic Items"]
195
196 # Create player sprite
197 self.player_sprite = PlayerSprite()
198
199 # Set player location
200 grid_x = 1
201 grid_y = 1
202 self.player_sprite.center_x = SPRITE_SIZE * grid_x + SPRITE_SIZE / 2
203 self.player_sprite.center_y = SPRITE_SIZE * grid_y + SPRITE_SIZE / 2
204 # Add to player sprite list
205 self.player_list.append(self.player_sprite)
206
207 # --- Pymunk Physics Engine Setup ---
208
209 # The default damping for every object controls the percent of velocity
210 # the object will keep each second. A value of 1.0 is no speed loss,
211 # 0.9 is 10% per second, 0.1 is 90% per second.
212 # For top-down games, this is basically the friction for moving objects.
213 # For platformers with gravity, this should probably be set to 1.0.
214 # Default value is 1.0 if not specified.
215 damping = DEFAULT_DAMPING
216
217 # Set the gravity. (0, 0) is good for outer space and top-down.
218 gravity = (0, -GRAVITY)
219
220 # Create the physics engine
221 self.physics_engine = arcade.PymunkPhysicsEngine(damping=damping, gravity=gravity)
222
223 # Add the player.
224 # For the player, we set the damping to a lower value, which increases
225 # the damping rate. This prevents the character from traveling too far
226 # after the player lets off the movement keys.
227 # Setting the moment of inertia to PymunkPhysicsEngine.MOMENT_INF prevents it from
228 # rotating.
229 # Friction normally goes between 0 (no friction) and 1.0 (high friction)
230 # Friction is between two objects in contact. It is important to remember
231 # in top-down games that friction moving along the 'floor' is controlled
232 # by damping.
233 self.physics_engine.add_sprite(
234 self.player_sprite,
235 friction=PLAYER_FRICTION,
236 mass=PLAYER_MASS,
237 moment_of_inertia=arcade.PymunkPhysicsEngine.MOMENT_INF,
238 collision_type="player",
239 max_horizontal_velocity=PLAYER_MAX_HORIZONTAL_SPEED,
240 max_vertical_velocity=PLAYER_MAX_VERTICAL_SPEED,
241 )
242
243 # Create the walls.
244 # By setting the body type to PymunkPhysicsEngine.STATIC the walls can't
245 # move.
246 # Movable objects that respond to forces are PymunkPhysicsEngine.DYNAMIC
247 # PymunkPhysicsEngine.KINEMATIC objects will move, but are assumed to be
248 # repositioned by code and don't respond to physics forces.
249 # Dynamic is default.
250 self.physics_engine.add_sprite_list(
251 self.wall_list,
252 friction=WALL_FRICTION,
253 collision_type="wall",
254 body_type=arcade.PymunkPhysicsEngine.STATIC,
255 )
256
257 # Create the items
258 self.physics_engine.add_sprite_list(
259 self.item_list, friction=DYNAMIC_ITEM_FRICTION, collision_type="item"
260 )
261
262 def on_key_press(self, key, modifiers):
263 """Called whenever a key is pressed."""
264
265 if key == arcade.key.LEFT:
266 self.left_pressed = True
267 elif key == arcade.key.RIGHT:
268 self.right_pressed = True
269 elif key == arcade.key.UP:
270 # find out if player is standing on ground
271 if self.physics_engine.is_on_ground(self.player_sprite):
272 # She is! Go ahead and jump
273 impulse = (0, PLAYER_JUMP_IMPULSE)
274 self.physics_engine.apply_impulse(self.player_sprite, impulse)
275
276 def on_key_release(self, key, modifiers):
277 """Called when the user releases a key."""
278
279 if key == arcade.key.LEFT:
280 self.left_pressed = False
281 elif key == arcade.key.RIGHT:
282 self.right_pressed = False
283
284 def on_update(self, delta_time):
285 """Movement and game logic"""
286
287 is_on_ground = self.physics_engine.is_on_ground(self.player_sprite)
288 # Update player forces based on keys pressed
289 if self.left_pressed and not self.right_pressed:
290 # Create a force to the left. Apply it.
291 if is_on_ground:
292 force = (-PLAYER_MOVE_FORCE_ON_GROUND, 0)
293 else:
294 force = (-PLAYER_MOVE_FORCE_IN_AIR, 0)
295 self.physics_engine.apply_force(self.player_sprite, force)
296 # Set friction to zero for the player while moving
297 self.physics_engine.set_friction(self.player_sprite, 0)
298 elif self.right_pressed and not self.left_pressed:
299 # Create a force to the right. Apply it.
300 if is_on_ground:
301 force = (PLAYER_MOVE_FORCE_ON_GROUND, 0)
302 else:
303 force = (PLAYER_MOVE_FORCE_IN_AIR, 0)
304 self.physics_engine.apply_force(self.player_sprite, force)
305 # Set friction to zero for the player while moving
306 self.physics_engine.set_friction(self.player_sprite, 0)
307 else:
308 # Player's feet are not moving. Therefore up the friction so we stop.
309 self.physics_engine.set_friction(self.player_sprite, 1.0)
310
311 # Move items in the physics engine
312 self.physics_engine.step()
313
314 def on_draw(self):
315 """Draw everything"""
316 self.clear()
317 self.wall_list.draw()
318 self.bullet_list.draw()
319 self.item_list.draw()
320 self.player_list.draw()
321
322
323def main():
324 """Main function"""
325 window = GameWindow(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
326 window.setup()
327 arcade.run()
328
329
330if __name__ == "__main__":
331 main()