Why Node is being added below the detected plane in ARKit

时间:2019-01-18 18:26:49

标签: ios arkit scnnode

I am working on an ARKit app where I am detecting a plane and now I want to place an object on top of the plane. The object does gets added on the plane but it is little bit under the plane. I can add the height/2 of the box and it will fix the issue, but wondering if there is a more easier way.

enter image description here

private func addBox(at position: SCNVector3) {

    let box = SCNBox(width: 0.2, height: 0.2, length: 0.2, chamferRadius: 0)
    let material = SCNMaterial()
    material.diffuse.contents = UIColor.red

    let boxNode = SCNNode(geometry: box)
    boxNode.position = position
    self.sceneView.scene.rootNode.addChildNode(boxNode)
}

@objc func tapped(recognizer :UITapGestureRecognizer) {

    let touch = recognizer.location(in: self.sceneView)

    if let nodeHitTest = self.sceneView.hitTest(touch, options: nil).first, nodeHitTest.node.name != "plane" {
        print("node")

        print(nodeHitTest.node)

    } else if let planeHitTest = self.sceneView.hitTest(touch, types: .estimatedHorizontalPlane).first {

        let position = SCNVector3(planeHitTest.worldTransform.columns.3.x, planeHitTest.worldTransform.columns.3.y, planeHitTest.worldTransform.columns.3.z)

        addBox(at: position)

        print("plane found")
    }

}

1 个答案:

答案 0 :(得分:1)

When you're setting the position of a SCNNode, you're defining position of the node's center point and that's the reason your node is vertically in the middle of the plane.

Adding half of the node's height to the y-axis is probably a very easy way to place the node on the plane as you already mentioned:

let position = SCNVector3(planeHitTest.worldTransform.columns.3.x,
                          planeHitTest.worldTransform.columns.3.y + Float(box.height/2), 
                          planeHitTest.worldTransform.columns.3.z)