+4 votes

For design reasons, I have to get the center of the current camera without getting a reference to its node (not known at advance).

Si I tried this:

var camera = get_viewport().get_camera()

But it returns null Oo
So I tried something else, like this:

var vtrans = get_viewport_transform()
var top_left = -vtrans.get_origin() / vtrans.get_scale()

# Then, to get the center, add half the size of the visible area?
var vsize = get_viewport_rect().size
var cam_pos = top_left + 0.5*vsize/vtrans.get_scale()

Well... works fine, as long as I don't resize the window. If I do, it produces an offset.
And it happens because get_viewport_rect().size is not the actual size in pixels of the screen, but a fixed value.
I can't use OS.get_window_size() either, because it doesn't takes display options into account.

So at this point, I could eventually recompute the size with all possible display options, but... is there something simpler than that?
Any idea how to get the center of the current camera without knowing where it is in the scene tree?

in Engine by (29,120 points)

I think there was an issue about a get_camera2d() function..

1 Answer

+8 votes

Answering myself:
Use canvas transform!

func _get_camera_center():
    var vtrans = get_canvas_transform()
    var top_left = -vtrans.get_origin() / vtrans.get_scale()
    var vsize = get_viewport_rect().size
    return top_left + 0.5*vsize/vtrans.get_scale()

Not sure why get_camera() returns null, though.

by (29,120 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.