拖动3d物体

该代码段展示了在Unity3D中处理用户触摸事件来与3D场景交互的方法。通过EventTouch事件获取屏幕位置,使用Raycast进行模型交互检测,并将屏幕坐标转换为世界坐标,实现物体选择与拖动功能。
摘要由CSDN通过智能技术生成
 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);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值