首页 文章

用 SceneKit 和 ARKit 创建一个盒子

提问于
浏览
2

我试图用 SceneKit 和 ARKit 创建一个原语。无论出于什么原因,它都不起作用。

let box = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0)

    let node = SCNNode(geometry: box)

    node.position = SCNVector3(0,0,0)

    sceneView.scene.rootNode.addChildNode(node)

我还需要输入相机坐标吗?

2 回答

  • 5

    您的代码看起来不错,它应该可以工作。我已经尝试了以下代码:用 ARKit 模板创建新应用后,我已经替换了函数 viewDidLoad。

    override func viewDidLoad() {
        super.viewDidLoad()
    
        // Set the view's delegate
        sceneView.delegate = self
    
        let box = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0)
        let node = SCNNode(geometry: box)
        node.position = SCNVector3(0,0,0)
        sceneView.scene.rootNode.addChildNode(node)
    }
    

    它在原始点(0、0、0)处创建一个框。不幸的是,您的设备在盒子里,因此您无法直视该盒子。要查看该框,请将设备移远一点。

    所附图片是移动设备后的方框:

    在此处输入图片说明

    如果您想立即看到它,请将框移到前面一点,添加颜色并使第一个材料为双面(以便从侧面或侧面看到它):

    let box = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0)
        box.firstMaterial?.diffuse.contents = UIColor.red
        box.firstMaterial?.isDoubleSided = true
        let boxNode = SCNNode(geometry: box)
        boxNode.position = SCNVector3(0, 0, -1)
        sceneView.scene.rootNode.addChildNode(boxNode)
    
  • 2

    您应该点击位置并使用世界坐标正确放置立方体。我不确定(0,0,0)是否是 ARKit 的正常位置。您可以尝试如下操作:
    将其放在您的 viewDidLoad 中:

    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapFrom))
    tapGestureRecognizer.numberOfTapsRequired = 1
    self.sceneView.addGestureRecognizer(tapGestureRecognizer)
    

    然后添加此方法:

    @objc func handleTapFrom(recognizer: UITapGestureRecognizer) {
        let tapPoint = recognizer.location(in: self.sceneView)
        let result = self.sceneView.hitTest(tapPoint, types: ARHitTestResult.ResultType.existingPlaneUsingExtent)
    
        if result.count == 0 {
            return
        }
    
        let hitResult = result.first
    
        let box = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0)
    
        let node = SCNNode(geometry: box)
        node.physicsBody = SCNPhysicsBody(type: SCNPhysicsBodyType.static, shape: nil)
        node.position = SCNVector3Make(hitResult.worldTransform.columns.3.x, hitResult.worldTransform.columns.3.y, hitResult.worldTransform.columns.3.z)
    
        sceneView.scene.rootNode.addChildNode(node)
    }
    

    然后,当您点击检测到的平面时,它将在您点击的平面上添加一个框。

相关问题