Get center of the current camera2d?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Zylann
:warning: Old Version Published before Godot 3 was released.

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?

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

timoschwarzer | 2016-07-26 15:32

:bust_in_silhouette: Reply From: Zylann

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.