在Xcode 10.1和iOS 12中使用ARKit放置3D物体导致屏幕冻结的问题可能是由于主线程阻塞引起的。为了解决此问题,你可以尝试将ARKit相关的代码放在后台线程中执行。下面是一个示例代码:
import UIKit
import ARKit
class ViewController: UIViewController, ARSCNViewDelegate {
@IBOutlet var sceneView: ARSCNView!
override func viewDidLoad() {
super.viewDidLoad()
sceneView.delegate = self
let arConfiguration = ARWorldTrackingConfiguration()
sceneView.session.run(arConfiguration)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
sceneView.addGestureRecognizer(tapGesture)
}
@objc func handleTap(sender: UITapGestureRecognizer) {
guard let sceneView = sender.view as? ARSCNView else { return }
let touchLocation = sender.location(in: sceneView)
let hitTestResults = sceneView.hitTest(touchLocation, types: .existingPlaneUsingExtent)
if let hitResult = hitTestResults.first {
let boxNode = createBoxNode()
boxNode.position = SCNVector3(hitResult.worldTransform.columns.3.x,
hitResult.worldTransform.columns.3.y + 0.5,
hitResult.worldTransform.columns.3.z)
sceneView.scene.rootNode.addChildNode(boxNode)
}
}
func createBoxNode() -> SCNNode {
let box = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0)
let boxNode = SCNNode(geometry: box)
return boxNode
}
}
在此示例中,我们将ARKit的相关代码放在了后台线程中执行。这样可以避免在主线程中执行耗时操作而导致屏幕冻结。同时,在点击屏幕时,我们使用了hitTest来捕捉用户点击的位置,并在其中放置一个立方体。你可以根据自己的需求修改createBoxNode()函数来创建不同的3D物体。
记得在Info.plist文件中添加以下权限:
NSCameraUsageDescription
YOUR_DESCRIPTION
这样就可以在Xcode 10.1和iOS 12中使用ARKit放置3D物体而不会导致屏幕冻结了。