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