[Godot] 3D拾取

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)
相关推荐
多恩Stone3 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
多恩Stone4 天前
【3D-AICG 系列-15】Trellis 2 的 O-voxel Shape: Flexible Dual Grid 代码与论文对应
人工智能·python·算法·3d·aigc
在下胡三汉4 天前
为什么“资产土地”标准化主资产的 glTF、glb格式模型,为什么非常流行
3d
2401_863801464 天前
3DTiles(.b3dm,i3dm,cmpt) 数据转换fbx转obj转max转su,cesium格式模型转换
3d
3Dmax效果图渲染研习社4 天前
2026年3ds Max云渲染平台哪个好?
3d
思茂信息4 天前
基于CST 3D Combined功能的以太网口RE仿真
开发语言·javascript·单片机·嵌入式硬件·matlab·3d
CG_MAGIC4 天前
Maya 角色绑定:控制器搭建与 IK/FK 切换
3d·贴图·maya·渲云渲染
PHOSKEY5 天前
光子精密3D工业相机陶瓷基片平面度检测!赋能电子制造质控升级
平面·3d·3d工业相机
twe77582585 天前
用3D动画揭示技术路线的多样性
科技·3d·制造·动画