Move with a Scrolling Screen - Margins#

Unlike the Move with a Scrolling Screen - Centered which centers the camera on the player, this example only moves the camera if the user gets within so many pixels of the edge. It allows for a ‘box’ in the middle where the user can move around and NOT move the camera.

Screen shot of using a scrolling window
sprite_move_scrolling_box.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_box
  8"""
  9
 10import random
 11import arcade
 12
 13SPRITE_SCALING = 0.5
 14
 15DEFAULT_SCREEN_WIDTH = 800
 16DEFAULT_SCREEN_HEIGHT = 600
 17SCREEN_TITLE = "Sprite Move with Scrolling Screen Example"
 18
 19# How many pixels to keep as a minimum margin between the character
 20# and the edge of the screen.
 21VIEWPORT_MARGIN = 200
 22
 23# How fast the camera pans to the player. 1.0 is instant.
 24CAMERA_SPEED = 0.1
 25
 26# How fast the character moves
 27PLAYER_MOVEMENT_SPEED = 7
 28
 29
 30class MyGame(arcade.Window):
 31    """ Main application class. """
 32
 33    def __init__(self, width, height, title):
 34        """
 35        Initializer
 36        """
 37        super().__init__(width, height, title, resizable=True)
 38
 39        # Sprite lists
 40        self.player_list = None
 41        self.wall_list = None
 42
 43        # Set up the player
 44        self.player_sprite = None
 45
 46        self.physics_engine = None
 47
 48        # Used in scrolling
 49        self.view_bottom = 0
 50        self.view_left = 0
 51
 52        # Track the current state of what key is pressed
 53        self.left_pressed = False
 54        self.right_pressed = False
 55        self.up_pressed = False
 56        self.down_pressed = False
 57
 58        self.camera_sprites = arcade.SimpleCamera()
 59        self.camera_gui = arcade.SimpleCamera()
 60
 61    def setup(self):
 62        """ Set up the game and initialize the variables. """
 63
 64        # Sprite lists
 65        self.player_list = arcade.SpriteList()
 66        self.wall_list = arcade.SpriteList()
 67
 68        # Set up the player
 69        self.player_sprite = arcade.Sprite(":resources:images/animated_characters/female_person/femalePerson_idle.png",
 70                                           scale=0.4)
 71        self.player_sprite.center_x = 256
 72        self.player_sprite.center_y = 512
 73        self.player_list.append(self.player_sprite)
 74
 75        # -- Set up several columns of walls
 76        for x in range(200, 1650, 210):
 77            for y in range(0, 1600, 64):
 78                # Randomly skip a box so the player can find a way through
 79                if random.randrange(5) > 0:
 80                    wall = arcade.Sprite(":resources:images/tiles/grassCenter.png", scale=SPRITE_SCALING)
 81                    wall.center_x = x
 82                    wall.center_y = y
 83                    self.wall_list.append(wall)
 84
 85        self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.wall_list)
 86
 87        # Set the background color
 88        self.background_color = arcade.color.AMAZON
 89
 90        # Set the viewport boundaries
 91        # These numbers set where we have 'scrolled' to.
 92        self.view_left = 0
 93        self.view_bottom = 0
 94
 95    def on_draw(self):
 96        """
 97        Render the screen.
 98        """
 99
100        # This command has to happen before we start drawing
101        self.clear()
102
103        # Select the camera we'll use to draw all our sprites
104        self.camera_sprites.use()
105
106        # Draw all the sprites.
107        self.wall_list.draw()
108        self.player_list.draw()
109
110        # Select the (unscrolled) camera for our GUI
111        self.camera_gui.use()
112
113        # Draw the GUI
114        arcade.draw_rectangle_filled(self.width // 2, 20, self.width, 40, arcade.color.ALMOND)
115        text = f"Scroll value: ({self.camera_sprites.position[0]:5.1f}, {self.camera_sprites.position[1]:5.1f})"
116        arcade.draw_text(text, 10, 10, arcade.color.BLACK_BEAN, 20)
117
118        # Draw the box that we work to make sure the user stays inside of.
119        # This is just for illustration purposes. You'd want to remove this
120        # in your game.
121        left_boundary = VIEWPORT_MARGIN
122        right_boundary = self.width - VIEWPORT_MARGIN
123        top_boundary = self.height - VIEWPORT_MARGIN
124        bottom_boundary = VIEWPORT_MARGIN
125        arcade.draw_lrbt_rectangle_outline(left_boundary, right_boundary, bottom_boundary, top_boundary,
126                                           arcade.color.RED, 2)
127
128    def on_key_press(self, key, modifiers):
129        """Called whenever a key is pressed. """
130
131        if key == arcade.key.UP:
132            self.up_pressed = True
133        elif key == arcade.key.DOWN:
134            self.down_pressed = True
135        elif key == arcade.key.LEFT:
136            self.left_pressed = True
137        elif key == arcade.key.RIGHT:
138            self.right_pressed = True
139
140    def on_key_release(self, key, modifiers):
141        """Called when the user releases a key. """
142
143        if key == arcade.key.UP:
144            self.up_pressed = False
145        elif key == arcade.key.DOWN:
146            self.down_pressed = False
147        elif key == arcade.key.LEFT:
148            self.left_pressed = False
149        elif key == arcade.key.RIGHT:
150            self.right_pressed = False
151
152    def on_update(self, delta_time):
153        """ Movement and game logic """
154
155        # Calculate speed based on the keys pressed
156        self.player_sprite.change_x = 0
157        self.player_sprite.change_y = 0
158
159        if self.up_pressed and not self.down_pressed:
160            self.player_sprite.change_y = PLAYER_MOVEMENT_SPEED
161        elif self.down_pressed and not self.up_pressed:
162            self.player_sprite.change_y = -PLAYER_MOVEMENT_SPEED
163        if self.left_pressed and not self.right_pressed:
164            self.player_sprite.change_x = -PLAYER_MOVEMENT_SPEED
165        elif self.right_pressed and not self.left_pressed:
166            self.player_sprite.change_x = PLAYER_MOVEMENT_SPEED
167
168        # Call update on all sprites (The sprites don't do much in this
169        # example though.)
170        self.physics_engine.update()
171
172        # Scroll the screen to the player
173        self.scroll_to_player()
174
175    def scroll_to_player(self):
176        """
177        Scroll the window to the player.
178        This method will attempt to keep the player at least VIEWPORT_MARGIN
179        pixels away from the edge.
180
181        if CAMERA_SPEED is 1, the camera will immediately move to the desired position.
182        Anything between 0 and 1 will have the camera move to the location with a smoother
183        pan.
184        """
185
186        # --- Manage Scrolling ---
187
188        # Scroll left
189        left_boundary = self.view_left + VIEWPORT_MARGIN
190        if self.player_sprite.left < left_boundary:
191            self.view_left -= left_boundary - self.player_sprite.left
192
193        # Scroll right
194        right_boundary = self.view_left + self.width - VIEWPORT_MARGIN
195        if self.player_sprite.right > right_boundary:
196            self.view_left += self.player_sprite.right - right_boundary
197
198        # Scroll up
199        top_boundary = self.view_bottom + self.height - VIEWPORT_MARGIN
200        if self.player_sprite.top > top_boundary:
201            self.view_bottom += self.player_sprite.top - top_boundary
202
203        # Scroll down
204        bottom_boundary = self.view_bottom + VIEWPORT_MARGIN
205        if self.player_sprite.bottom < bottom_boundary:
206            self.view_bottom -= bottom_boundary - self.player_sprite.bottom
207
208        # Scroll to the proper location
209        position = self.view_left, self.view_bottom
210        self.camera_sprites.move_to(position, CAMERA_SPEED)
211
212    def on_resize(self, width: int, height: int):
213        """
214        Resize window
215        Handle the user grabbing the edge and resizing the window.
216        """
217        self.camera_sprites.resize(width, height)
218        self.camera_gui.resize(width, height)
219
220
221def main():
222    """ Main function """
223    window = MyGame(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT, SCREEN_TITLE)
224    window.setup()
225    arcade.run()
226
227
228if __name__ == "__main__":
229    main()