美文网首页
iOS ARKit 手势拖动、旋转、缩放3D模型

iOS ARKit 手势拖动、旋转、缩放3D模型

作者: 慧煎蛋 | 来源:发表于2019-03-19 19:12 被阅读0次
    ar手势
    基于官方ARKit文档里的示例代码

    Swift4.2核心手势代码如下

        override public func viewDidLoad() {
            super.viewDidLoad()
            
            sceneView.addGestureRecognizer(UIPinchGestureRecognizer.init(target: self, action: #selector(pinchDo)))//缩放
            sceneView.addGestureRecognizer(UIPanGestureRecognizer.init(target: self, action: #selector(panGuestDo)))
            sceneView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(tapGuestDo)))
        }
    
        @objc func pinchDo(_ pinch: UIPinchGestureRecognizer) {//捏合缩放
            guard let curObj = objM.lastUsedObject else { return }
            
            
            if pinch.state == .began {//每次捏合手势开始重新获取
                beginPinchScale = pinch.scale//手势开始时获取当前模型的scale
                beginObjScale = curObj.scale.x//手势开始时获取手势的比例scale
            }
            
            if pinch.state == .changed {
                //计算, 当前手势scale除以手势开始时的scale, 以开始时模型的scale为基准相乘, 实现圆润的放大缩小效果
                var scale = beginObjScale*Float(pinch.scale/beginPinchScale)
                scale = scale<0.5 ? 0.5 : scale
                scale = scale>2 ? 2 : scale
                curObj.scale = SCNVector3.init(scale, scale, scale)
            }
        }
        
        @objc func panGuestDo(_ GG: UIPanGestureRecognizer) {//拖动手势
            guard let curObj = objM.lastUsedObject else { return }
    
            let location = GG.location(in: sceneView)
            let velocityPoint = GG.velocity(in: sceneView)
    
            switch GG.state {
            case .changed:
                if let touchedObj = virtualObject(at: location, inSceV: sceneView) {//位移
                    objM.translate(touchedObj, in: sceneView, basedOn: location, instantly: true)//位移方法
                    objM.lastUsedObject = touchedObj//自定义模型管理类
                }else{//旋转
                    let xx = Float(velocityPoint.x/5000)//支持空白处水平x轴滑动旋转
                    let yy = Float(velocityPoint.y/5000)//支持空白处垂直y轴滑动旋转
                    curObj.eulerAngles.y += abs(xx) > abs(yy) ? xx : -yy
                }
            case .ended:
                return
            default:
                return
            }
        }
    
        var beginObjScale: Float = 1
        var beginPinchScale: CGFloat = 1
        @IBOutlet var sceneView: ARSCNView!
    

    相关文章

      网友评论

          本文标题:iOS ARKit 手势拖动、旋转、缩放3D模型

          本文链接:https://www.haomeiwen.com/subject/cnlydqtx.html