Camera3D - project_position: calculating z_depth param

Godot Version



I am using this code to let a MeshInstance3D (mark) follow the mouse position but can’t figure out how to calculate the z_depth parameter:

func _unhandled_input(event):
	if event is InputEventMouseMotion:

# cam: orthogonal projection, fixed rotation: -45, 45, 0
func mark_set(pos):
	var _pos = cam.project_position(pos, 150)
	mark.transform.origin.x = _pos.x
	mark.transform.origin.z = _pos.z

You’re going to need to cast a ray from the camera using this projection information. Basically you use a raycast collision hit with the scene to get the exact world-space position to set your object to.

There’s a ray-casting tutorial in the docs which covers this (last example in “Raycast query”):


if result:
    # move object to result.position
    # or do additional checks / logic

I am aware of raycasting and could use that, but I came across the Camera3D’s project_position function and would like to figure out how it works.

I don’t think this is the intended use case for project_position. To get the z_depth at an arbitrary point in the scene, you need to compare a raycast intersection to the corresponding origin position on the camera’s plane. You can do that, but at the end of it you end up just working backward into the raycast intersection again with extra steps.

Example (after raycast):

var originPos = cam.project_position(get_viewport().get_mouse_position(), 0)
var z = (_originPos - result.position).length()
var _pos = cam.project_position(get_viewport().get_mouse_position(), z)

This is functionally identical to:

var _pos = result.position