【发布时间】:2020-10-05 02:26:08
【问题描述】:
我一直在学习 Swift 和 ARKit,所以请原谅我草率的编码。我使用下面的两个教程来创建我现有的代码。我从第一个开始,然后在第二个视频的最后出现错误。 youtuber没有发生这种情况,所以我不确定我哪里出错了。 完整的错误显示“实例成员 'addChild' 不能用于类型 'AnchorEntity';您的意思是改用这种类型的值吗?”
- https://www.youtube.com/watch?v=J7hRooEVBhU&list=WL&index=1)
- https://www.youtube.com/watch?v=8l3J9lwaecY)
任何帮助都是极大的 感激不尽!
import UIKit
import RealityKit
import ARKit
class ViewController: UIViewController {
@IBOutlet var arView: ARView!
override func viewDidLoad() {
super.viewDidLoad()
arView.session.delegate = self
showModel()
overlayCoachingView()
setupARView()
arView.addGestureRecognizer(UITapGestureRecognizer(target: self, action:
#selector(handleTap(recognizer:))))
}
func showModel(){
let anchorEntity = AnchorEntity(plane: .horizontal, minimumBounds:[0.2, 0.2])
let entity = try! Entity.loadModel(named: "fender_stratocaster")
entity.setParent(anchorEntity)
arView.scene.addAnchor(anchorEntity)
}
func overlayCoachingView () {
let coachingView = ARCoachingOverlayView(frame: CGRect(x: 0, y: 0, width:
arView.frame.width, height: arView.frame.height))
coachingView.session = arView.session
coachingView.activatesAutomatically = true
coachingView.goal = .horizontalPlane
view.addSubview(coachingView)
}
// Load the "Box" scene from the "Experience" Reality File
// let boxAnchor = try! Experience.loadBox()
// Add the box anchor to the scene
//arView.scene.anchors.append(boxAnchor)
func setupARView(){
arView.automaticallyConfigureSession = false
let configuration = ARWorldTrackingConfiguration()
configuration.planeDetection = [.horizontal, .vertical]
configuration.environmentTexturing = .automatic
arView.session.run(configuration)
}
//object placement
@objc
func handleTap(recognizer: UITapGestureRecognizer){
let location = recognizer.location(in:arView)
let results = arView.raycast(from: location, allowing: .estimatedPlane, alignment:
.horizontal)
if let firstResult = results.first {
let anchor = ARAnchor(name: "fender_stratocaster", transform:
firstResult.worldTransform)
arView.session.add(anchor: anchor)
} else {
print("Object placement failed - couldn't find surface.")
}
}
func placeObject(named entityName: String, for anchor: ARAnchor) {
let entity = try! ModelEntity.loadModel(named: entityName)
entity.generateCollisionShapes(recursive: true)
arView.installGestures([.rotation, .translation], for: entity)
let anchorEntity = AnchorEntity(anchor: anchor)
AnchorEntity.addChild(entity)
arView.scene.addAnchor(anchorEntity)
}
}
extension ViewController: ARSessionDelegate {
func session( session: ARSession, didAdd anchors: [ARAnchor]) {
for anchor in anchors {
if let anchorName = anchor.name, anchorName == "fender_stratocaster" {
placeObject(named: anchorName, for: anchor)
} }
}
}
【问题讨论】:
标签: swift xcode augmented-reality arkit realitykit