Show node in center of camera viewport

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

Hi,
I have a 2D tilemap with a player character. The player character has a camera attached which follows his movement.

I want to display a map node above the player sprite when the hotkey is pressed (centered in the camera).

The problem is I can’t calculate the correct centered position inside the camera.

When I try to center it by using visible rect of camera viewport, I get some fixed position that doesn’t change once the player has moved. Here’s the code:

map_pos.x = get_node("Camera2D").get_viewport().get_visible_rect().size.x - map.get_node("Panel").get_size().x

map_pos.y = get_node("Camera2D").get_viewport().get_visible_rect().size.y - map.get_node("Panel").get_size().y

How can I calculate the center coordinates of the camera viewport, and put something in them?

Thanks.

Just to clarify - what I need is to calculate the coordinates inside the viewport and then transform them to global coordinates so that the node ends up in the center of viewport.

Antonb | 2017-12-23 11:45

:bust_in_silhouette: Reply From: Antonb

OK,
My mistake was adding the new node under root, and not under Camera2D. The final code looks like this:

map = load("res://scenes/map/map.tscn").instance()

Then:

get_node(“Camera2D”).add_child(map)

Then:

var map_pos = Vector2()

map_pos.x = get_node("Camera2D").get_viewport().get_visible_rect().size.width/2 - map.get_node("Panel").get_size().width/2

map_pos.y = get_node("Camera2D").get_viewport().get_visible_rect().size.height/2 - map.get_node("Panel").get_size().height/2
map.set_pos(Vector2(map_pos))