CoreLocation heading base on back camera (Augmented reality)

后端 未结 2 1922
盖世英雄少女心
盖世英雄少女心 2020-12-04 23:05

I would like to create an augmented reality view that is going to point an object in a direction. However, the CoreLocation heading is not working correctly when you are fac

2条回答
  •  时光说笑
    2020-12-04 23:49

    To save anyone else's time, here's Chee's answer in Swift:

    import GLKit    
    
    func headingCorrectedForTilt() -> Float?{
            guard let motion = self.motionManager.deviceMotion else{
                return nil
            }
    
            let aspect = fabsf(Float(self.view.bounds.width / self.view.bounds.height))
            let projectionMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(45.0), aspect, 0.1, 100)
    
    
            let r = motion.attitude.rotationMatrix
            let camFromIMU = GLKMatrix4Make(Float(r.m11), Float(r.m12), Float(r.m13), 0,
                               Float(r.m21), Float(r.m22), Float(r.m23), 0,
                               Float(r.m31), Float(r.m32), Float(r.m33), 0,
                               0,     0,     0,     1)
    
            let viewFromCam = GLKMatrix4Translate(GLKMatrix4Identity, 0, 0, 0);
            let imuFromModel = GLKMatrix4Identity
            let viewModel = GLKMatrix4Multiply(imuFromModel, GLKMatrix4Multiply(camFromIMU, viewFromCam))
            var isInvertible : Bool = false
            let modelView = GLKMatrix4Invert(viewModel, &isInvertible);
            var viewport = [Int32](count:4,repeatedValue: 0)
    
            viewport[0] = 0;
            viewport[1] = 0;
            viewport[2] = Int32(self.view.frame.size.width);
            viewport[3] = Int32(self.view.frame.size.height);
    
            var success: Bool = false
            let vector3 = GLKVector3Make(Float(self.view.frame.size.width)/2, Float(self.view.frame.size.height)/2, 1.0)
            let calculatedPoint = GLKMathUnproject(vector3, modelView, projectionMatrix, &viewport, &success)
    
            return success ? atan2f(-calculatedPoint.y, calculatedPoint.x) : nil
        }
    

提交回复
热议问题