ARKit:如何在iPhone和它之间的范围内删除对象

时间:2018-02-15 05:41:51

标签: ios swift arkit

放置了三个对象,当我的iPhone和对象之间的范围为0.5时,我想删除其中一个对象。

override func viewDidLoad() {
    super.viewDidLoad()

    let scene = SCNScene()
    scene.rootNode.name = "RootNode"
    sceneView.scene = scene
    sceneView.delegate = self
    sceneView.scene.physicsWorld.contactDelegate = self

    let x = floatBetween(-0.5, and: 0.5)
    self.addNewObject(at: x, y: -0.3, nodeName: "A")
    self.addNewObject(at: x, y: -0.3, nodeName: "B")
    self.addNewObject(at: x, y: -0.3, nodeName: "C")

    for i in scene.rootNode.childNodes {
        print("NAME", i.name ?? "nil")
    }
}


func renderer(_ renderer: SCNSceneRenderer, didRenderScene scene: SCNScene, atTime time: TimeInterval) {

    let distance = self.getUserVector().1
    print("hellooooooooooooo", sceneView.scene.rootNode.childNodes.count)
    let hitResults = sceneView.hitTest(sceneView.center, options: [:])

    print(hitResults)

    guard !hitResults.isEmpty else { return }
    guard let node = hitResults.first?.node else { return }

    if node.name == "A" && node.position.distance(from: distance) <= 0.5 {
        node.removeFromParentNode()
    }

    if node.name == "B" && node.position.distance(from: distance) <= 0.5 {
        node.removeFromParentNode()
    }

    if node.name == "C" && node.position.distance(from: distance) <= 0.5 {
        node.removeFromParentNode()
    }

}

使用此方法,将为新节点分配唯一的名称和位置,并将其放置在虚拟空间中。

func addNewObject(at x: Float, y: Float, nodeName: String) {
    let cubeNode = Ship()
    cubeNode.name = nodeName
    cubeNode.position = SCNVector3(x, y, y) // SceneKit/AR coordinates are in meters
    sceneView.scene.rootNode.addChildNode(cubeNode)
}

此处,此代码用于获取用户的方向和位置。

func getUserVector() -> (SCNVector3, SCNVector3) { // (direction, position)
    if let frame = self.sceneView.session.currentFrame {
        let mat = SCNMatrix4(frame.camera.transform)
        // 4x4 transform matrix describing camera in world space
        let dir = SCNVector3(-1 * mat.m31, -1 * mat.m32, -1 * mat.m33)
        // orientation of camera in world space
        let pos = SCNVector3(mat.m41, mat.m42, mat.m43)
        // location of camera in world space
        return (dir, pos)
    }
    return (SCNVector3(0, 0, -1), SCNVector3(0, 0, -0.2))
}

func floatBetween(_ first: Float,  and second: Float) -> Float {
    //
    return (Float(arc4random()) / Float(UInt32.max)) * (first - second) + second
}

extension SCNVector3 {

func distance(from vector: SCNVector3) -> Float {
    let x = self.x - vector.x
    let y = self.y - vector.y
    let z = self.z - vector.z
    return sqrtf((x * x) + (y + y) + (z + z))
}

删除一个对象后,将同时删除所有其他对象。为什么会这样?我正确命名他们。删除一个节点的最佳方法是什么?

由于

0 个答案:

没有答案