Godot Version
v4.4.dev2.official [97ef3c837]
Question
Hi! I’m working on a random level generator in 3D where I position items with a random z and viewport position that is then translated to 3D space, something like this (simplified):
# ensure the camera is ready
await $Camera3D.ready
# get the viewport rectangle
var viewportRect := get_viewport().get_visible_rect()
for i in num_items:
# make some item
var item = load(path).instantiate()
# get a random z position
var z := randf_range(minZ, maxZ)
# get a random x position in the viewport bounds
var viewportX := randf_range(
viewportRect.position.x,
viewportRect.position.x + viewportRect.size.x
)
# get the 3d x position that corresponds to the above viewport x position at the given z depth
item.position.x = $Camera3D.project_position(Vector2(viewportX, 0), z).x
# for simplicity, let's assume the y position is 0
item.position.y = 0
# apply the above random z position
item.position.z = z
# add the item to the scene tree
add_child.call_deferred(item)
This works really well and the script creates a number of items in random z
and x
positions and a fixed y
position.
I then turned this into a @tool
so that I could play with variables in the editor and have the level re-create in real-time. This also works well, with one caveat: in the editor, the viewportRect.size
is x: 2, y: 2
.
When I run the game, the size is either the “viewport width/height” or “window width/height override” from the project settings (the default values being 1152 × 648). That makes sense.
With a viewportRect.size
of 2 × 2, the result is very different. Items are much more clustered in the middle. Items that are close to the camera converge towards the centre, forming a triangular formation on the ground plane rather than a trapezoid.
I tried to use the values from the project settings, e.g. ProjectSettings.get_setting("display/window/size/viewport_width")
, but that doesn’t work at all in the editor. The items get positioned off-screen far into the distance to the left (large negative x values).
Maybe I’m just misunderstanding the viewport dimensions. I don’t get why these would be 2 × 2 in the editor but proper window pixel sizes when running the game.
Any hint would be much appreciated.
The result in the editor:
Editor top view:
The result when I run the game (much better positioned without the obvious triangular converging):