如何获取ARKit相机当前旋转?竖屏模式下横握角度异常求解
解决ARKit相机朝向在横握设备(未切换系统横竖屏)时的角度偏差问题
嘿,这个问题我之前做AR项目时也踩过坑!核心原因其实很简单:ARKit 里相机的 eulerAngles 是基于设备的自然竖屏方向来计算的——哪怕你只是横握设备但没切换系统的横竖屏模式,它的参考坐标系还是保持竖屏时的状态,导致你取的角度轴对应关系完全乱了,自然就出现偏差。
下面是我亲测有效的解决方案:
核心思路
我们需要根据用户当前的设备握持方向,对相机的姿态矩阵做坐标系转换,把它从「设备自然竖屏坐标系」转换为「用户当前握持的坐标系」,再从转换后的矩阵里提取角度,这样不管怎么握设备,得到的朝向角度都是符合预期的。
具体步骤&代码示例
1. 开启设备方向监听
首先要能获取用户当前的握持方向,我们需要监听设备方向变化:
import UIKit import ARKit class ARViewController: UIViewController, ARSessionDelegate { var arView: ARView! override func viewDidLoad() { super.viewDidLoad() arView = ARView(frame: view.bounds) view.addSubview(arView) arView.session.delegate = self // 开启设备方向监听 UIDevice.current.beginGeneratingDeviceOrientationNotifications() NotificationCenter.default.addObserver( self, selector: #selector(deviceOrientationChanged), name: UIDevice.orientationDidChangeNotification, object: nil ) } @objc private func deviceOrientationChanged() { // 方向变化时可以在这里更新相关逻辑,或者在获取角度时实时判断 } // 记得销毁监听 deinit { UIDevice.current.endGeneratingDeviceOrientationNotifications() NotificationCenter.default.removeObserver(self) } }
2. 校正相机姿态并提取角度
接下来,我们编写一个方法,根据当前握持方向校正相机姿态,再提取你需要的朝向角度:
private func getCorrectedCameraOrientation() -> (yaw: Float, pitch: Float, roll: Float) { guard let currentFrame = arView.session.currentFrame else { return (0, 0, 0) } let cameraTransform = currentFrame.camera.transform var correctionMatrix = simd_float4x4.identity let deviceOrientation = UIDevice.current.orientation // 根据握持方向创建对应的旋转校正矩阵 switch deviceOrientation { case .landscapeLeft: // 横握,Home键在左侧:绕Z轴旋转90度(π/2弧度) correctionMatrix = simd_float4x4(rotationAngle: .pi / 2, axis: SIMD3<Float>(0, 0, 1)) case .landscapeRight: // 横握,Home键在右侧:绕Z轴旋转-90度 correctionMatrix = simd_float4x4(rotationAngle: -.pi / 2, axis: SIMD3<Float>(0, 0, 1)) case .portraitUpsideDown: // 竖屏倒握:绕Z轴旋转180度 correctionMatrix = simd_float4x4(rotationAngle: .pi, axis: SIMD3<Float>(0, 0, 1)) default: // 竖屏正握或未知方向:无需校正 break } // 应用校正矩阵到相机姿态 let correctedTransform = correctionMatrix * cameraTransform // 从校正后的矩阵提取欧拉角(顺序:roll绕X轴, pitch绕Y轴, yaw绕Z轴) let eulerAngles = simd_euler_angles(correctedTransform) return (yaw: eulerAngles.z, pitch: eulerAngles.y, roll: eulerAngles.x) }
3. 使用校正后的角度
现在你可以在需要的地方调用这个方法,比如在session(_:didUpdate:)代理里实时获取:
func session(_ session: ARSession, didUpdate frame: ARFrame) { let correctedAngles = getCorrectedCameraOrientation() // 根据你的需求使用对应的角度,比如原来的eulerAngles[1]对应的是pitch,现在取correctedAngles.pitch print("校正后的pitch角度:\(correctedAngles.pitch)") }
注意事项
- 如果你发现角度方向不对(比如正负反了),可以调整旋转矩阵的角度符号(比如把
.pi/2改成-.pi/2),这个和你的具体需求场景有关。 - 当
UIDevice.current.orientation返回.unknown时,我们默认按竖屏处理,你也可以根据自己的业务逻辑做更严谨的判断。
这样处理后,不管你是竖握还是横握设备,只要系统没切换横竖屏,得到的相机朝向角度都会和你的预期一致啦!
内容的提问来源于stack exchange,提问作者Salmiak
相关产品推荐
相关产品推荐

