How do I offset the 2D camera based on the direction the player is facing?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By DPJB

For reference, you can look at some Nintendo platformers as an example(2D Mario games, 2D Metroid games, etc). If you notice, the player is never centered in the middle of the camera’s view. Instead, the camera is offset slightly so that the player can see more of the current level in the direction they are facing than what’s behind them.

I have a platformer set up with a camera that follows the player and sticks to the bounds of the level, however I can’t figure out how to implement the offset I want. I tried playing with the offset in the camera’s properties and also with code but it just made a glitched mess.

Does anyone know how to implement this?

:bust_in_silhouette: Reply From: skysphr

From what I understand you want a camera that:

  1. If the player is facing leftwards, is centered around and follows a point left to the player
  2. If the player is facing rightwards, do the same but in the other direction
  3. As the player changes directions, the camera should move at a constant speed towards the point it needs to follow.

More or less pseudocode:

var screen_width = get_viewport_rect().size.x
var camera_target
var target_distance = 100 # You can use screen_width if you want 1/x of the screen etc.
var camera_speed = 6 # Multiply with delta if you want pixels/second
if <<< player is moving right >>> :
    camera_target = $Player.position.x + target_distance - screen_width/2
    $Camera.offset.x = min($Camera.offset.x + camera_speed, camera_target)
else:
    camera_target = $Player.position.x - target_distance - screen_width/2
    $Camera.offset.x = max($Camera.offset.x - camera_speed, camera_target)
$Camera.offset.y = $Player.position.y

Yup, that’s exactly what I want, thanks. I will try the code.

DPJB | 2021-09-26 18:59

Is this supposed to go inside the _process() function or somewhere else?

DPJB | 2021-09-26 19:09

Yeah, it should be in process.

skysphr | 2021-09-27 11:24