Camera Use in a Platformer

Screen shot of using a scrolling window
camera_platform.py
  1"""
  2Camera Example
  3
  4Artwork from: https://kenney.nl
  5Tiled available from: https://www.mapeditor.org/
  6
  7If Python and Arcade are installed, this example can be run from the command line with:
  8python -m arcade.examples.camera_platform
  9"""
 10
 11import time
 12
 13import arcade
 14
 15TILE_SCALING = 0.5
 16PLAYER_SCALING = 0.5
 17
 18SCREEN_WIDTH = 800
 19SCREEN_HEIGHT = 600
 20
 21SCREEN_TITLE = "Camera Example"
 22SPRITE_PIXEL_SIZE = 128
 23GRID_PIXEL_SIZE = SPRITE_PIXEL_SIZE * TILE_SCALING
 24
 25# How many pixels to keep as a minimum margin between the character
 26# and the edge of the screen.
 27VIEWPORT_MARGIN_TOP = 60
 28VIEWPORT_MARGIN_BOTTOM = 60
 29VIEWPORT_RIGHT_MARGIN = 270
 30VIEWPORT_LEFT_MARGIN = 270
 31
 32# Physics
 33MOVEMENT_SPEED = 5
 34JUMP_SPEED = 23
 35GRAVITY = 1.1
 36
 37# Map Layers
 38LAYER_NAME_PLATFORMS = "Platforms"
 39LAYER_NAME_COINS = "Coins"
 40LAYER_NAME_BOMBS = "Bombs"
 41
 42
 43class MyGame(arcade.Window):
 44    """Main application class."""
 45
 46    def __init__(self):
 47        """
 48        Initializer
 49        """
 50        super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE, resizable=True)
 51
 52        # Our TileMap Object
 53        self.tile_map = None
 54
 55        # Our Scene Object
 56        self.scene = None
 57
 58        # Set up the player
 59        self.score = 0
 60        self.player_sprite = None
 61
 62        self.physics_engine = None
 63        self.top_of_map = 0
 64        self.end_of_map = 0
 65        self.game_over = False
 66        self.last_time = None
 67        self.frame_count = 0
 68        self.fps_message = None
 69
 70        # Cameras
 71        self.camera: arcade.camera.Camera2D = None
 72        self.gui_camera = None
 73
 74        self.camera_shake = None
 75
 76        self.shake_offset_1 = 0
 77        self.shake_offset_2 = 0
 78        self.shake_vel_1 = 0
 79        self.shake_vel_2 = 0
 80
 81        # Text
 82        self.text_fps = arcade.Text(
 83            "",
 84            x=10,
 85            y=40,
 86            color=arcade.color.BLACK,
 87            font_size=14,
 88        )
 89        self.text_score = arcade.Text(
 90            f"Score: {self.score}",
 91            x=10,
 92            y=20,
 93            color=arcade.color.BLACK,
 94            font_size=14,
 95        )
 96
 97    def setup(self):
 98        """Set up the game and initialize the variables."""
 99
100        # Map name
101        map_name = ":resources:tiled_maps/level_1.json"
102
103        # Layer Specific Options for the Tilemap
104        layer_options = {
105            LAYER_NAME_PLATFORMS: {
106                "use_spatial_hash": True,
107            },
108            LAYER_NAME_COINS: {
109                "use_spatial_hash": True,
110            },
111            LAYER_NAME_BOMBS: {
112                "use_spatial_hash": True,
113            },
114        }
115
116        # Load in TileMap
117        self.tile_map = arcade.load_tilemap(map_name, TILE_SCALING, layer_options)
118
119        # Initiate New Scene with our TileMap, this will automatically add all layers
120        # from the map as SpriteLists in the scene in the proper order.
121        self.scene = arcade.Scene.from_tilemap(self.tile_map)
122
123        # Set up the player
124        self.player_sprite = arcade.Sprite(
125            ":resources:images/animated_characters/female_person/femalePerson_idle.png",
126            scale=PLAYER_SCALING,
127        )
128
129        # Starting position of the player
130        self.player_sprite.center_x = 196
131        self.player_sprite.center_y = 128
132        self.scene.add_sprite("Player", self.player_sprite)
133
134        self.camera = arcade.camera.Camera2D()
135        self.gui_camera = arcade.camera.Camera2D()
136
137        self.camera_shake = arcade.camera.grips.ScreenShake2D(self.camera.view_data,
138                                                              max_amplitude=12.5,
139                                                              acceleration_duration=0.05,
140                                                              falloff_time=0.20,
141                                                              shake_frequency=15.0)
142
143        # Center camera on user
144        self.pan_camera_to_user()
145
146        # Calculate the right edge of the my_map in pixels
147        self.top_of_map = self.tile_map.height * GRID_PIXEL_SIZE
148        self.end_of_map = self.tile_map.width * GRID_PIXEL_SIZE
149
150        # --- Other stuff
151        # Set the background color
152        if self.tile_map.background_color:
153            self.background_color = self.tile_map.background_color
154
155        # Keep player from running through the wall_list layer
156        self.physics_engine = arcade.PhysicsEnginePlatformer(
157            self.player_sprite,
158            self.scene.get_sprite_list(LAYER_NAME_PLATFORMS),
159            gravity_constant=GRAVITY,
160        )
161
162        self.game_over = False
163
164    def on_resize(self, width, height):
165        """Resize window"""
166        self.camera.projection = self.gui_camera.projection = (-width/2, width/2, -height/2, height/2)
167        self.camera.viewport = self.gui_camera.viewport = (0, 0, width, height)
168
169    def on_draw(self):
170        """Render the screen."""
171        self.clear()
172
173        self.camera_shake.update_camera()
174        self.camera.use()
175
176        # Draw our Scene
177        self.scene.draw()
178
179        # Readjust the camera so the screen shake doesn't affect
180        # the camera following algorithm.
181        self.camera_shake.readjust_camera()
182
183        self.gui_camera.use()
184
185        # Update fps text periodically
186        if self.last_time and self.frame_count % 60 == 0:
187            fps = 1.0 / (time.time() - self.last_time) * 60
188            self.text_fps.text = f"FPS: {fps:5.2f}"
189
190        self.text_fps.draw()
191
192        if self.frame_count % 60 == 0:
193            self.last_time = time.time()
194
195        # Draw Score
196        self.text_score.draw()
197
198        # Draw game over
199        if self.game_over:
200            arcade.draw_text("Game Over", self.width/2, self.height/2, arcade.color.BLACK,
201                             30)
202
203        self.frame_count += 1
204
205    def on_key_press(self, key, modifiers):
206        """
207        Called whenever a key is pressed
208        """
209        if key == arcade.key.UP:
210            if self.physics_engine.can_jump():
211                self.player_sprite.change_y = JUMP_SPEED
212        elif key == arcade.key.LEFT:
213            self.player_sprite.change_x = -MOVEMENT_SPEED
214        elif key == arcade.key.RIGHT:
215            self.player_sprite.change_x = MOVEMENT_SPEED
216
217    def on_key_release(self, key, modifiers):
218        """
219        Called when the user presses a mouse button.
220        """
221        if key == arcade.key.LEFT or key == arcade.key.RIGHT:
222            self.player_sprite.change_x = 0
223
224    def pan_camera_to_user(self, panning_fraction: float = 1.0):
225        """
226        Manage Scrolling
227
228        :param panning_fraction: Number from 0 to 1. Higher the number, faster we
229                                 pan the camera to the user.
230        """
231
232        # This spot would center on the user
233        screen_center_x, screen_center_y = self.player_sprite.position
234        if screen_center_x < self.camera.viewport_width/2:
235            screen_center_x = self.camera.viewport_width/2
236        if screen_center_y < self.camera.viewport_height/2:
237            screen_center_y = self.camera.viewport_height/2
238        user_centered = screen_center_x, screen_center_y
239
240        self.camera.position = arcade.math.lerp_2d(self.camera.position, user_centered, panning_fraction)
241
242    def on_update(self, delta_time):
243        """Movement and game logic"""
244
245        if self.player_sprite.right >= self.end_of_map:
246            self.game_over = True
247
248        # Call update on all sprites
249        if not self.game_over:
250            self.physics_engine.update()
251            self.camera_shake.update(delta_time)
252
253        coins_hit = arcade.check_for_collision_with_list(
254            self.player_sprite, self.scene.get_sprite_list("Coins")
255        )
256        for coin in coins_hit:
257            coin.remove_from_sprite_lists()
258            self.score += 1
259
260        # Bomb hits
261        bombs_hit = arcade.check_for_collision_with_list(
262            self.player_sprite, self.scene.get_sprite_list("Bombs")
263        )
264        for bomb in bombs_hit:
265            bomb.remove_from_sprite_lists()
266            self.camera_shake.start()
267
268        # Pan to the user
269        self.pan_camera_to_user(panning_fraction=0.12)
270
271        # Update score text
272        self.text_score.text = f"Score: {self.score}"
273
274
275def main():
276    """Get this game started."""
277    window = MyGame()
278    window.setup()
279    arcade.run()
280
281
282if __name__ == "__main__":
283    main()