How can I get a Camera2D to rotate around its parent based on the cursor's position?

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

I am trying to figure out how to get my Camera2D to rotate around my player based on the position of the mouse. Basically, I have six directions for my character: right, left, down-right, down-left, up-right, and up-left. I already have this part working. However, I want to have the camera be in a certain position around the player based on what direction the player is facing (i.e. when the player’s direction is up-right, the player would be in the lower-left corner of the screen and the part that is visible would be what is up and to the right of the player, when the player’s direction is up-left, the player would be in the lower-right corner, etc). However, I simply can’t figure it out. Could someone please help me?

:bust_in_silhouette: Reply From: Thomas Karcher

If I understand you correctly, you don’t actually want to “rotate” the camera, but change the camera offset based on the mouse position, right? In this case, your code in the player node (with the current camera being a child of this node) could look something like this:

const CAMERA_OFFSET = Vector2(300, 200)

func _process (_delta):
    # Calculate the difference between player position and mouse position
    var diff = get_viewport().get_mouse_position() - get_global_transform_with_canvas().origin
    # set the offset to a fixed distance from the player 
    diff = diff / diff.length() * CAMERA_OFFSET
    # update the camera offset
    $Camera2D.offset = diff