GODOT: Positioning 3D Object at Screen Edge

Viewed 78

I want to place a plane mesh at the left edge of the screen. How do I calculate the position and set it using GDScript?

1 Answers

You can get the current Camera with get_viewport().get_camera().

And you can ask a Camera for its viewing volume with get_frustum(), which returns an array with the planes, in the following order: near, far, left, top, right, bottom.

Now, you say left edge… That would be the segment from the near-left-top intersection to the near-left-bottom intersection. So we use the intersect_3 method of the Plane class.

At viola:

var camera := viewport.get_camera()
var planes := camera.get_frustum() 
var near_plane := planes[0]
var left_plane := planes[2]
var top_plane := planes[3]
var bottom_plane := planes[5]

var near_left_top := near_plane.intersect_3(left_plane, top_plane)
var near_left_bottom := near_plane.intersect_3(left_plane, bottom_plane)

There near_left_top and near_left_bottom would be Vector3, in global coordinates, that represent the left edge of the screen in space.


By the way you can ask a Plane for its normal, for example:

var left_normal := left_plane.normal

We can use that to build a Basis. Something like this (this might not be the way you want to arrange the axis):

var axis_y := (near_left_bottom - near_left_top).normalized()
var axis_z := left_normal
var axis_x := axis_y.cross(axis_z)
var basis := Basis(axis_x, axis_y, axis_z)

And then you just need a position to make a transform. For example (this might not be the position you want):

var origin := (near_left_bottom + near_left_top) * 0.5
var plane_transform := Transform(basis, origin)

And then set it as the global_transform of your MeshInstance or whatever.


I doubt this is exactly how you want it, but I hope I have given you enough information to adapt it to your needs.

By the way, I'll remind you that the simplest way to have something follow the Camera is to make it a child of the Camera.

Related