CollisionObject3D文档
Camera3D文档
CollisionObject3D有个信号_input_event,可以用于处理3D拾取。
Camera3D也有project_position用于将屏幕空间坐标投影到3D空间。
gdscript
extends Node3D
#是否处于选中状态
var selected : bool = false
#摄像机的前向量
var front : Vector3 = Vector3(0.0, 0.0, -1.0)
#待拾取的对象
@onready var a : CollisionObject3D = $a
#标记,表示在3D物体上的位置
@onready var mark : MeshInstance3D = $mark
func _on_a_mouse_entered() -> void:
print("entered")
mark.visible = true
func _on_a_mouse_exited() -> void:
print("exited")
mark.visible = false
func _on_a_input_event(camera: Node, event: InputEvent, position: Vector3, normal: Vector3, shape_idx: int) -> void:
var str = \
"camera: " + str(camera) + "\n" + \
"event: " + str(event) + "\n" + \
"position: " + str(position) + "\n" + \
"normal: " + str(normal) + "\n" + \
"shape_idx: " + str(shape_idx) + "\n" + \
"a.position: " + str(a.position)
$mark.position = position
$label.text = str
if event is InputEventMouseButton:
if event.button_index == MOUSE_BUTTON_LEFT:
if event.pressed:
selected = true
else:
selected = false
elif event is InputEventMouseMotion:
if selected:
var c : Camera3D = camera as Camera3D
#由相机指向物体的向量
var dir : Vector3 = a.position - c.position
#dir投影到front上所得的长度
var dis : float = front.dot(dir)
#将位置投影到3D空间
a.position = c.project_position(event.position, dis)