private touchStart(e: EventTouch): void {
let position = e.getLocation();
const outRay = new geometry.Ray();
let ray = Camera.mainCamera.screenPointToRay(position.x, position.y, outRay);
let result = geometry.intersect.rayModel(ray, this.meshRenderer.model);
if (result)
this.chooseBuild = true;
}
private touchMove(e: EventTouch): void {
if (!this.chooseBuild) return;
this.screenToWorldPosition(e);
}
public screenToWorldPosition(event: EventTouch): Vec3 {
// let screenPoint = event.getLocation();
//求出摄像机和当前拖动物体的方向
// let direction = Vec3.subtract(_vec3Temp1, this.node.worldPosition, Camera.mainCamera.node.worldPosition);
//拖动物体投影在direction上的投影长度
//let length = Vec3.dot(direction, Camera.mainCamera.node.forward);
//物体离摄像机近裁面/摄像机远裁面和近裁面的距离
// let zRate = (length - Camera.mainCamera.near) / (Camera.mainCamera.far - Camera.mainCamera.near);
// _vec3Temp1.set(screenPoint .x, screenPoint .y, zRate);
//屏幕坐标转成3d坐标
// let outPos = Camera.mainCamera.screenToWorld(_vec3Temp1);
// 上面的方法从屏幕坐标转成3d坐标,需要传入3d拖动物体的坐标,以下方法不用
let screenPoint = event.getLocation()
const outRay = new geometry.Ray();
Camera.mainCamera.screenPointToRay(screenPoint.x, screenPoint.y, outRay);
let x = outRay.o.x + (0 - outRay.o.y) / outRay.d.y * outRay.d.x;
let z = outRay.o.z + (0 - outRay.o.y) / outRay.d.y * outRay.d.z;
return new Vec3(x, 0, z);
}
拖动3d物体
于 2023-05-14 22:49:00 首次发布
该代码段展示了在Unity3D中处理用户触摸事件来与3D场景交互的方法。通过EventTouch事件获取屏幕位置,使用Raycast进行模型交互检测,并将屏幕坐标转换为世界坐标,实现物体选择与拖动功能。
摘要由CSDN通过智能技术生成