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