Skip to main content
Engineering LibreTexts

9.20: Camera Slack, and Moving the Camera View

  • Page ID
    14638
  •         # adjust camerax and cameray if beyond the "camera slack"
            playerCenterx = playerObj['x'] + int(playerObj['size'] / 2)
            playerCentery = playerObj['y'] + int(playerObj['size'] / 2)
            if (camerax + HALF_WINWIDTH) - playerCenterx > CAMERASLACK:
                camerax = playerCenterx + CAMERASLACK - HALF_WINWIDTH
            elif playerCenterx - (camerax + HALF_WINWIDTH) > CAMERASLACK:
                camerax = playerCenterx - CAMERASLACK - HALF_WINWIDTH
            if (cameray + HALF_WINHEIGHT) - playerCentery > CAMERASLACK:
                cameray = playerCentery + CAMERASLACK - HALF_WINHEIGHT
            elif playerCentery - (cameray + HALF_WINHEIGHT) > CAMERASLACK:
                cameray = playerCentery - CAMERASLACK - HALF_WINHEIGHT
    

    The camera’s position (which is stored as integers in the camerax and cameray variables) needs to be updated when the player moves over. I’ve called the number of pixels the player can move before the camera gets updated the "camera slack". Line 19 set the CAMERASLACK constant to 90, which our program will take to mean that the player squirrel can move 90 pixels from the center before the camera position gets updated to follow the squirrel.

    In order to understand the equations used in the if statements on lines 4 [172], 6 [174], 8 [176], and 10 [178], you should note that (camerax + HALF_WINWIDTH) and (cameray + HALF_WINHEIGHT) are the XY game world coordinates currently at the center of the screen. The playerCenterx and playerCentery is set to the middle of the player’s squirrel’s position, also in game world coordinates.

    For line 4 [172], if the center X coordinate minus the player’s center X coordinate is greater than the CAMERASLACK value, that means the player is more pixels to the right of the center of the camera than the camera slack should allow. The camerax value needs to be updated so that the player squirrel is just at the edge of the camera slack. This is why line 5 [173] sets camerax to playerCenterx + CAMERASLACK – HALF_WINWIDTH. Note that the camerax variable is changed, not the playerObj['x'] value. We want to move the camera, not the player.

    The other three if statements follow similar logic for the left, up and down sides.

    • Was this article helpful?