pymunk_demo_platformer_07.py Full Listing
pymunk_demo_platformer_07.py
1"""
2Example of Pymunk Physics Engine Platformer
3"""
4from typing import Optional
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
58class GameWindow(arcade.Window):
59 """ Main Window """
60
61 def __init__(self, width, height, title):
62 """ Create the variables """
63
64 # Init the parent class
65 super().__init__(width, height, title)
66
67 # Player sprite
68 self.player_sprite: Optional[arcade.Sprite] = None
69
70 # Sprite lists we need
71 self.player_list: Optional[arcade.SpriteList] = None
72 self.wall_list: Optional[arcade.SpriteList] = None
73 self.bullet_list: Optional[arcade.SpriteList] = None
74 self.item_list: Optional[arcade.SpriteList] = None
75
76 # Track the current state of what key is pressed
77 self.left_pressed: bool = False
78 self.right_pressed: bool = False
79
80 # Physics engine
81 self.physics_engine = Optional[arcade.PymunkPhysicsEngine]
82
83 # Set background color
84 self.background_color = arcade.color.AMAZON
85
86 def setup(self):
87 """ Set up everything with the game """
88
89 # Create the sprite lists
90 self.player_list = arcade.SpriteList()
91 self.bullet_list = arcade.SpriteList()
92
93 # Map name
94 map_name = ":resources:/tiled_maps/pymunk_test_map.json"
95
96 # Load in TileMap
97 tile_map = arcade.load_tilemap(map_name, SPRITE_SCALING_TILES)
98
99 # Pull the sprite layers out of the tile map
100 self.wall_list = tile_map.sprite_lists["Platforms"]
101 self.item_list = tile_map.sprite_lists["Dynamic Items"]
102
103 # Create player sprite
104 self.player_sprite = arcade.Sprite(":resources:images/animated_characters/female_person/femalePerson_idle.png",
105 SPRITE_SCALING_PLAYER)
106 # Set player location
107 grid_x = 1
108 grid_y = 1
109 self.player_sprite.center_x = SPRITE_SIZE * grid_x + SPRITE_SIZE / 2
110 self.player_sprite.center_y = SPRITE_SIZE * grid_y + SPRITE_SIZE / 2
111 # Add to player sprite list
112 self.player_list.append(self.player_sprite)
113
114 # --- Pymunk Physics Engine Setup ---
115
116 # The default damping for every object controls the percent of velocity
117 # the object will keep each second. A value of 1.0 is no speed loss,
118 # 0.9 is 10% per second, 0.1 is 90% per second.
119 # For top-down games, this is basically the friction for moving objects.
120 # For platformers with gravity, this should probably be set to 1.0.
121 # Default value is 1.0 if not specified.
122 damping = DEFAULT_DAMPING
123
124 # Set the gravity. (0, 0) is good for outer space and top-down.
125 gravity = (0, -GRAVITY)
126
127 # Create the physics engine
128 self.physics_engine = arcade.PymunkPhysicsEngine(damping=damping,
129 gravity=gravity)
130
131 # Add the player.
132 # For the player, we set the damping to a lower value, which increases
133 # the damping rate. This prevents the character from traveling too far
134 # after the player lets off the movement keys.
135 # Setting the moment of inertia to PymunkPhysicsEngine.MOMENT_INF prevents it from
136 # rotating.
137 # Friction normally goes between 0 (no friction) and 1.0 (high friction)
138 # Friction is between two objects in contact. It is important to remember
139 # in top-down games that friction moving along the 'floor' is controlled
140 # by damping.
141 self.physics_engine.add_sprite(self.player_sprite,
142 friction=PLAYER_FRICTION,
143 mass=PLAYER_MASS,
144 moment_of_inertia=arcade.PymunkPhysicsEngine.MOMENT_INF,
145 collision_type="player",
146 max_horizontal_velocity=PLAYER_MAX_HORIZONTAL_SPEED,
147 max_vertical_velocity=PLAYER_MAX_VERTICAL_SPEED)
148
149 # Create the walls.
150 # By setting the body type to PymunkPhysicsEngine.STATIC the walls can't
151 # move.
152 # Movable objects that respond to forces are PymunkPhysicsEngine.DYNAMIC
153 # PymunkPhysicsEngine.KINEMATIC objects will move, but are assumed to be
154 # repositioned by code and don't respond to physics forces.
155 # Dynamic is default.
156 self.physics_engine.add_sprite_list(self.wall_list,
157 friction=WALL_FRICTION,
158 collision_type="wall",
159 body_type=arcade.PymunkPhysicsEngine.STATIC)
160
161 # Create the items
162 self.physics_engine.add_sprite_list(self.item_list,
163 friction=DYNAMIC_ITEM_FRICTION,
164 collision_type="item")
165
166 def on_key_press(self, key, modifiers):
167 """Called whenever a key is pressed. """
168
169 if key == arcade.key.LEFT:
170 self.left_pressed = True
171 elif key == arcade.key.RIGHT:
172 self.right_pressed = True
173 elif key == arcade.key.UP:
174 # find out if player is standing on ground
175 if self.physics_engine.is_on_ground(self.player_sprite):
176 # She is! Go ahead and jump
177 impulse = (0, PLAYER_JUMP_IMPULSE)
178 self.physics_engine.apply_impulse(self.player_sprite, impulse)
179
180 def on_key_release(self, key, modifiers):
181 """Called when the user releases a key. """
182
183 if key == arcade.key.LEFT:
184 self.left_pressed = False
185 elif key == arcade.key.RIGHT:
186 self.right_pressed = False
187
188 def on_update(self, delta_time):
189 """ Movement and game logic """
190
191 is_on_ground = self.physics_engine.is_on_ground(self.player_sprite)
192 # Update player forces based on keys pressed
193 if self.left_pressed and not self.right_pressed:
194 # Create a force to the left. Apply it.
195 if is_on_ground:
196 force = (-PLAYER_MOVE_FORCE_ON_GROUND, 0)
197 else:
198 force = (-PLAYER_MOVE_FORCE_IN_AIR, 0)
199 self.physics_engine.apply_force(self.player_sprite, force)
200 # Set friction to zero for the player while moving
201 self.physics_engine.set_friction(self.player_sprite, 0)
202 elif self.right_pressed and not self.left_pressed:
203 # Create a force to the right. Apply it.
204 if is_on_ground:
205 force = (PLAYER_MOVE_FORCE_ON_GROUND, 0)
206 else:
207 force = (PLAYER_MOVE_FORCE_IN_AIR, 0)
208 self.physics_engine.apply_force(self.player_sprite, force)
209 # Set friction to zero for the player while moving
210 self.physics_engine.set_friction(self.player_sprite, 0)
211 else:
212 # Player's feet are not moving. Therefore up the friction so we stop.
213 self.physics_engine.set_friction(self.player_sprite, 1.0)
214
215 # Move items in the physics engine
216 self.physics_engine.step()
217
218 def on_draw(self):
219 """ Draw everything """
220 self.clear()
221 self.wall_list.draw()
222 self.bullet_list.draw()
223 self.item_list.draw()
224 self.player_list.draw()
225
226def main():
227 """ Main function """
228 window = GameWindow(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
229 window.setup()
230 arcade.run()
231
232
233if __name__ == "__main__":
234 main()