I want to position a 3D object at my mouse cursor. How can I do that in Godot? In Unity, I'd use
Camera3D.project_position is the Godot equivalent function.
Here's an implementation that can either move the position with fixed
orientation or can also point the cursor object. I'm using
_g to indicate
which values are in worldspace (global) to avoid confusion with localspace.
extends Node3D @onready var camera := get_parent() as Camera3D @export_range(1, 1000) var depth := 10.0 @export var should_only_set_position := false func _process(_dt): var mouse_pos = get_viewport().get_mouse_position() var cursor_pos_g = camera.project_position(mouse_pos, depth) if should_only_set_position: # To just position it, set global_position and set the desired # orientation in your scene. global_position = cursor_pos_g else: # To make the cursor point at the centre of the screen, ensure it faces # -z direction. var cam_forward_g = -camera.get_global_transform().basis.z var look_pos_g = camera.global_position + cam_forward_g * depth * 1.5 look_at_from_position(cursor_pos_g, look_pos_g)
Since Godot's forward direction is -z (?!), you need to point your cursor along the -z axis for it to be oriented correctly. (Notice
cam_forward_g is also -z.) If you have trouble, add some extra arms to make the orientation changes very obvious.
Cursor has the above script and it has some shapes underneath it to make it visible:
I put it under the camera, but you could also a export to let it live anywhere:
@export var camera : Camera3D instead.
You could also change this code to make
look_pos_g the global position of an object you're going to interact with or your player character.