Keeping 2 characters on the screen at the same position on the x axis

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

I’m relatively new to game dev, and am currently creating a small 2D multiplayer couch game, which involves a top down camera and 2 playable players both facing each other. I’ve already made it so the characters move in respect to way that they are facing, and am currently working on implementing a camera for this game. However, I am unsure how to keep the 2 players in the same position with respect to the camera regardless of their movement. for example if my first player moves left while player 2 stands still, my first playable character will rotate around the second player, I then want the camera to rotate with the players, so that player 1 and 2 are still at the same x axis position relative to the camera. This is primarily to keep a strong sense of spacing between the 2 players.

making the camera a child node of player 1 will allow the camera to rotate as intended, but will not keep player 2 on the screen once the player moves out of view. I’ve also tried a multitarget camera, but have been unable to rotate it with my players, instead of simply shifting it on the x and y axis. The only solution I’ve thought of is making a new kinematic body which is updated every frame to be the center of both players, and have it pointing towards player 2 and making the camera a child of this new kinematic body so that it rotates with it, but then again that does not account for how far the camera must zoom to keep both characters on screen. Any help would be greatly appreciated.

:bust_in_silhouette: Reply From: skysphr

Assuming camera is the camera, p1 and p2 are the players, and k is a zoom multiplication constant (at k=1, the players are displayed exactly on the edges of the screen):

camera.offset = (p1.position + p2.position) / 2
camera.rotation_degrees = rad2deg((p2.position - p1.position).angle())
var zoom = (p1.position - p2.position).length() / get_viewport_rect().size.x * k
camera.zoom = Vector2(zoom, zoom)

Make sure the camera has rotation enabled. This applies to landscape orientation.