How do I convert a global position to a position relative to a camera?

Godot Version

Godot 4.5.1-mono

Question

I’m trying to make it so that when the player (CharacterBody2D) moves past the edge of the screen, the camera will move once to follow, as if it is moving to another room, much like old adventure games like The Legend of Zelda or of course Atari’s Adventure. I have this working well, with one issue, I realized when writing my code I had been using the player’s global position, so the code basically works once when leaving the initial room, but won’t work again or go back to the previous room the way it should. Is there a way to convert the player’s position to something relative to the camera, so that it essentially checks if the player has reached the edge of the screen properly, rather than an arbitrary coordinate on the global plane?

I wrote a small function before that converts a global 2D node’s position into a position on the canvas layer, that might be useful for you!

public static Vector2 WorldToViewport(Node2D target)
{
    Vector2 targetCanvasPosition = target.GetScreenTransform()
        .Origin.Clamp(Vector2.Zero, target.GetViewportRect().Size);

    return targetCanvasPosition;
}

Ah, that works, thank you very much for the help!

1 Like