Projecting collision shape from camera, focal length/angle of view

Godot Version



I’d like to have a collider for an Area3D that projects from the camera to capture all visible, selectable units, to be placed in a dictionary. It looks like I can use a CollisionPolygon3D to create the shape programmatically. How would I calculate the position of the vertices according to where a ray cast shot from each corner of the viewport lands?

Maybe you can use the node VisibleOnScreenNotifier3D instead?

If not, use Camera3D.project_ray_origin() and Camera3D.project_ray_normal().
Example for one corner:

extends Camera3D
func _ready():
	var view_rect = get_viewport().get_visible_rect()
	var screen_v1 = Vector2(view_rect.position.x, view_rect.position.y)
	var v1_near = project_ray_origin(screen_v1) + project_ray_normal(screen_v1) * near
	var v1_far = v1_near + project_ray_normal(screen_v1) * (far - near)