How do I limit players' movement to camera space?

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

I’m making a 2d two player fighting game. I’ve managed to make a dynamic camera that zooms in and out depending on the distance between the players, and I’ve made it so there’s a maximum and minimum amount of zoom.

How do I keep both player characters within the screen at all times? The map is larger than the screen horizontally (this is important for a key element of the game), so I can’t just add bounds to the map that match the screen size.

:bust_in_silhouette: Reply From: ChrissWalters

I did not fully understand what is your problem here.

if you wanted to limit the players movement, add a collisionshape as boundry and connect it to the max camera distance, so that the collision boundry scales withe the camera distance to “ground”.

:bust_in_silhouette: Reply From: godot_dev_

@ChrissWalters’ answer makes sense. If the walls (StaticBody2Ds with CollisionShapes) hug the camera boundaries, then the players will never be able to leave the camera. In addition, you also have stage boundaries, so the players can’t leave those boundaries either.

Furthermore, I have worked with walls for a 2D fighter before. If you look in this video, the walls follow the camera (center of the players) with a delay. The way I achieved this is by having a script on the StaticBody2D of the wall continuously check its position in relation to the camera’s center and update its position to try and be relative to the center of both players with a slight delay (via a Tween). In your case, you want to avoid adding this artificial delay and simply snap the position of the camera boundary wall to the correct position. You can achieve this using the bounding box of camera and the position of the camera’s center. Below is some code to get camerea bounding rectangles and center that may help you (functions should be part of the script on the Camera2D):

  func computeScreenCenter():

       var minPos = computeMinimumPointBoundary()
       var maxPos = computeMaximumPointBoundary()

       var screenRect = Rect2(minPos,Vector2())
       screenRect = screenRect.expand(maxPos)
       return calculate_center(screenRect)



   func computeMinimumPointBoundary():
          # Get view rectangle
          var ctrans = get_canvas_transform()
          var min_pos = (-ctrans.get_origin() / ctrans.get_scale())
          return min_pos

   func computeMaximumPointBoundary():
          # Get view rectangle
          var ctrans = get_canvas_transform()
          var min_pos = -ctrans.get_origin() / ctrans.get_scale()

          var view_size = get_viewport_rect().size / ctrans.get_scale()
          var max_pos = min_pos + view_size

           return max_pos