From 06ea8d905eb2a4f44fa0cf786e53d2eede15fb8a Mon Sep 17 00:00:00 2001 From: Cameron Smart Date: Thu, 16 Apr 2020 16:33:32 -0700 Subject: [PATCH] Added scrolling --- platformer.py | 54 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/platformer.py b/platformer.py index cba2ba1..ff73da9 100644 --- a/platformer.py +++ b/platformer.py @@ -18,6 +18,14 @@ PLAYER_MOVEMENT_SPEED = 5 GRAVITY = 1 PLAYER_JUMP_SPEED = 20 +# How many pixels to keep as a minimum margin between the character +# and the edge of the screen. +LEFT_VIEWPORT_MARGIN = 250 +RIGHT_VIEWPORT_MARGIN = 250 +BOTTOM_VIEWPORT_MARGIN = 50 +TOP_VIEWPORT_MARGIN = 100 + + class MyGame(arcade.Window): """ @@ -41,6 +49,10 @@ class MyGame(arcade.Window): # Our physics engine self.physics_engine = None + # Used to keep track of our scrolling + self.view_bottom = 0 + self.view_left = 0 + arcade.set_background_color(arcade.csscolor.CORNFLOWER_BLUE) def setup(self): @@ -118,6 +130,48 @@ class MyGame(arcade.Window): # Move the player with the physics engine self.physics_engine.update() + # --- Manage Scrolling --- + + # Track if we need to change the viewport + + changed = False + + # Scroll left + left_boundary = self.view_left + LEFT_VIEWPORT_MARGIN + if self.player_sprite.left < left_boundary: + self.view_left -= left_boundary - self.player_sprite.left + changed = True + + # Scroll right + right_boundary = self.view_left + SCREEN_WIDTH - RIGHT_VIEWPORT_MARGIN + if self.player_sprite.right > right_boundary: + self.view_left += self.player_sprite.right - right_boundary + changed = True + + # Scroll up + top_boundary = self.view_bottom + SCREEN_HEIGHT - TOP_VIEWPORT_MARGIN + if self.player_sprite.top > top_boundary: + self.view_bottom += self.player_sprite.top - top_boundary + changed = True + + # Scroll down + bottom_boundary = self.view_bottom + BOTTOM_VIEWPORT_MARGIN + if self.player_sprite.bottom < bottom_boundary: + self.view_bottom -= bottom_boundary - self.player_sprite.bottom + changed = True + + if changed: + # Only scroll to integers. Otherwise we end up with pixels that + # don't line up on the screen + self.view_bottom = int(self.view_bottom) + self.view_left = int(self.view_left) + + # Do the scrolling + arcade.set_viewport(self.view_left, + SCREEN_WIDTH + self.view_left, + self.view_bottom, + SCREEN_HEIGHT + self.view_bottom) + def main(): """ Main method """