How to convert camera screen boundary to global position?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By zeruno

I am trying to spawn enemies at the edge of the camera. But I do not know how to get the edges of the camera as positions. I can get the middle of the screen using Camera.GetCameraScreenCenter() and the size of the camera viewport with Camera.GetViewport().Size. But since the viewport is in pixels, I do not know how to offset the screen center by 2D units.

I think when working in 2d the pixels are the units, unless you have done scaling to your nodes.

magicalogic | 2022-12-09 03:55

@magicalogic using your insight, I was able to solve this. If you write your comment as a post, I can mark it as best answer.

zeruno | 2022-12-09 15:32

:bust_in_silhouette: Reply From: exuin

just add / subtract half the size to the center to get the edges.

:bust_in_silhouette: Reply From: godot_dev_

The below code is how I achieved computing camera center and edge position calculations, maybe it can help you:



func computeScreenCenter():
	var minPos = computeMinimumPointBoundary()
	var maxPos = computeMaximumPointBoundary()
	var screenRect = Rect2(minPos,Vector2())
	screenRect = screenRect.expand(maxPos)
	return calculate_center(screenRect)



func computeMinimumPointBoundary():
	# Get view rectangle
	var ctrans = get_canvas_transform()
	var min_pos = (-ctrans.get_origin() / ctrans.get_scale())
	return min_pos

func computeMaximumPointBoundary():
	# Get view rectangle
	var ctrans = get_canvas_transform()
	var min_pos = -ctrans.get_origin() / ctrans.get_scale()
	var view_size = get_viewport_rect().size / ctrans.get_scale()
	var max_pos = min_pos + view_size
	return max_pos

func calculate_center(rect):
    return Vector2(
			rect.position.x + rect.size.x/2,
			rect.position.y + rect.size.y/2)

:bust_in_silhouette: Reply From: magicalogic

When working in 2d the pixels are the units, unless you have done scaling to your nodes.