+2 votes

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.

in Engine by (63 points)

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.

1 Answer

0 votes

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:

getnode("Camera2D").addchild(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))
by (63 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 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 webmaster@godotengine.org with your username.