Camera Shake#

Screen shot of using a scrolling window

You can cause the camera to shake, as this example does when the player encounters a bomb. See the highlighted lines below.

sprite_move_scrolling_shake.py#
  1"""
  2Scroll around a large screen.
  3
  4Artwork from https://kenney.nl
  5
  6If Python and Arcade are installed, this example can be run from the command line with:
  7python -m arcade.examples.sprite_move_scrolling_shake
  8"""
  9
 10import random
 11import math
 12import arcade
 13
 14SPRITE_SCALING = 0.5
 15
 16DEFAULT_SCREEN_WIDTH = 800
 17DEFAULT_SCREEN_HEIGHT = 600
 18SCREEN_TITLE = "Camera Shake Example"
 19
 20# How many pixels to keep as a minimum margin between the character
 21# and the edge of the screen.
 22VIEWPORT_MARGIN = 220
 23
 24# How fast the camera pans to the player. 1.0 is instant.
 25CAMERA_SPEED = 0.1
 26
 27# How fast the character moves
 28PLAYER_MOVEMENT_SPEED = 7
 29
 30BOMB_COUNT = 50
 31PLAYING_FIELD_WIDTH = 1600
 32PLAYING_FIELD_HEIGHT = 1600
 33
 34
 35class MyGame(arcade.Window):
 36    """ Main application class. """
 37
 38    def __init__(self, width, height, title):
 39        """
 40        Initializer
 41        """
 42        super().__init__(width, height, title, resizable=True)
 43
 44        # Sprite lists
 45        self.player_list = None
 46        self.wall_list = None
 47        self.bomb_list = None
 48
 49        # Set up the player
 50        self.player_sprite = None
 51
 52        # Physics engine so we don't run into walls.
 53        self.physics_engine = None
 54
 55        # Create the cameras. One for the GUI, one for the sprites.
 56        # We scroll the 'sprite world' but not the GUI.
 57        self.camera_sprites = arcade.Camera()
 58        self.camera_gui = arcade.Camera()
 59
 60        self.explosion_sound = arcade.load_sound(":resources:sounds/explosion1.wav")
 61
 62    def setup(self):
 63        """ Set up the game and initialize the variables. """
 64
 65        # Sprite lists
 66        self.player_list = arcade.SpriteList()
 67        self.wall_list = arcade.SpriteList()
 68        self.bomb_list = arcade.SpriteList()
 69
 70        # Set up the player
 71        self.player_sprite = arcade.Sprite(":resources:images/animated_characters/female_person/femalePerson_idle.png",
 72                                           scale=0.4)
 73        self.player_sprite.center_x = 512
 74        self.player_sprite.center_y = 512
 75        self.player_list.append(self.player_sprite)
 76
 77        # -- Set up several columns of walls
 78        for x in range(200, PLAYING_FIELD_WIDTH, 210):
 79            for y in range(0, PLAYING_FIELD_HEIGHT, 64):
 80                # Randomly skip a box so the player can find a way through
 81                if random.randrange(5) > 0:
 82                    wall = arcade.Sprite(":resources:images/tiles/grassCenter.png", scale=SPRITE_SCALING)
 83                    wall.center_x = x
 84                    wall.center_y = y
 85                    self.wall_list.append(wall)
 86
 87        for i in range(BOMB_COUNT):
 88            bomb = arcade.Sprite(":resources:images/tiles/bomb.png", scale=0.25)
 89            placed = False
 90            while not placed:
 91                bomb.center_x = random.randrange(PLAYING_FIELD_WIDTH)
 92                bomb.center_y = random.randrange(PLAYING_FIELD_HEIGHT)
 93                if not arcade.check_for_collision_with_list(bomb, self.wall_list):
 94                    placed = True
 95            self.bomb_list.append(bomb)
 96
 97        self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.wall_list)
 98
 99        # Set the background color
100        self.background_color = arcade.color.AMAZON
101
102    def on_draw(self):
103        """
104        Render the screen.
105        """
106
107        # This command has to happen before we start drawing
108        self.clear()
109
110        # Select the camera we'll use to draw all our sprites
111        self.camera_sprites.use()
112
113        # Draw all the sprites.
114        self.wall_list.draw()
115        self.bomb_list.draw()
116        self.player_list.draw()
117
118    def on_key_press(self, key, modifiers):
119        """Called whenever a key is pressed. """
120
121        if key == arcade.key.UP:
122            self.player_sprite.change_y = PLAYER_MOVEMENT_SPEED
123        elif key == arcade.key.DOWN:
124            self.player_sprite.change_y = -PLAYER_MOVEMENT_SPEED
125        elif key == arcade.key.LEFT:
126            self.player_sprite.change_x = -PLAYER_MOVEMENT_SPEED
127        elif key == arcade.key.RIGHT:
128            self.player_sprite.change_x = PLAYER_MOVEMENT_SPEED
129
130    def on_key_release(self, key, modifiers):
131        """Called when the user releases a key. """
132
133        if key == arcade.key.UP or key == arcade.key.DOWN:
134            self.player_sprite.change_y = 0
135        elif key == arcade.key.LEFT or key == arcade.key.RIGHT:
136            self.player_sprite.change_x = 0
137
138    def on_update(self, delta_time):
139        """ Movement and game logic """
140
141        # Call update on all sprites (The sprites don't do much in this
142        # example though.)
143        self.physics_engine.update()
144
145        # Scroll the screen to the player
146        self.scroll_to_player()
147
148        hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.bomb_list)
149        for bomb in hit_list:
150            # Remove the bomb and go 'boom'
151            bomb.remove_from_sprite_lists()
152            self.explosion_sound.play()
153
154            # --- Shake the camera ---
155            # Pick a random direction
156            shake_direction = random.random() * 2 * math.pi
157            # How 'far' to shake
158            shake_amplitude = 10
159            # Calculate a vector based on that
160            shake_vector = (
161                math.cos(shake_direction) * shake_amplitude,
162                math.sin(shake_direction) * shake_amplitude
163            )
164            # Frequency of the shake
165            shake_speed = 1.5
166            # How fast to damp the shake
167            shake_damping = 0.9
168            # Do the shake
169            self.camera_sprites.shake(shake_vector,
170                                      speed=shake_speed,
171                                      damping=shake_damping)
172
173    def scroll_to_player(self):
174        """
175        Scroll the window to the player.
176
177        if CAMERA_SPEED is 1, the camera will immediately move to the desired position.
178        Anything between 0 and 1 will have the camera move to the location with a smoother
179        pan.
180        """
181
182        position = (
183            self.player_sprite.center_x - self.width / 2,
184            self.player_sprite.center_y - self.height / 2
185        )
186        self.camera_sprites.move_to(position, CAMERA_SPEED)
187
188    def on_resize(self, width: int, height: int):
189        """
190        Resize window
191        Handle the user grabbing the edge and resizing the window.
192        """
193        self.camera_sprites.resize(width, height)
194        self.camera_gui.resize(width, height)
195
196
197def main():
198    """ Main function """
199    window = MyGame(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT, SCREEN_TITLE)
200    window.setup()
201    arcade.run()
202
203
204if __name__ == "__main__":
205    main()