2017-07-07 61 views
0

我正在尝试使用SceneKit和ARKit创建一个基本框。无论出于何种原因,它都不起作用。使用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

你应该得到点击的位置,并使用世界坐标来正确放置立方体。我不确定(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) 
} 

然后,当你上检测到的平面挖掘,它会添加一个盒子你挖掘的飞机。

+0

我有一个生成错误,改变了这一部分。它没有工作,所以我改变了这一点。 'node.position = SCNVector3Make((hitResult?.worldTransform.columns.3.x)!,(hitResult?.worldTransform.columns.3.y)!,(hitResult?.worldTransform.columns.3.z)! )' – ParalaxWobat

+0

然后呢? – OxyFlax

+0

它没有添加一个多维数据集。我正在尝试一些简单的方法来将AR添加到场景中。我不知道为什么它不起作用。 – ParalaxWobat

1

你的代码看起来不错,它应该工作。我尝试了下面的代码:使用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)处创建一个方框。不幸的是,您的设备在盒子内,因此您无法直接看到该盒子。要查看该框,请稍稍移动设备。

所附的图像是框移动我的设备后:

enter image description here

如果你想第一时间看到它,移动框前面一点,加色,使第一材料是双面(看到它,即使在或出方):

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) 
相关问题