如何在“ func renderer(SCNSceneRenderer,nodeFor:ARAnchor)-> SCNNode”中旋转SCNNode?

时间:2018-08-06 09:26:03

标签: ios swift xcode scenekit

因此,我能够在锚点位置放置一个盒子节点。 现在,如何在场景中旋转SCNNode?

我正在尝试修改节点的transform&eulerAngles,但是它们没有任何作用:

func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
    print("nodeFor anchor \(anchor)")

    guard anchor.name == "card" else { return nil }

    let colors = [
        UIColor.yellow, // front
        UIColor.red, // right
        UIColor.blue, // back
        UIColor.green, // left
        UIColor.purple, // top
        UIColor.gray] // bottom

    let sideMaterials = colors.map { color -> SCNMaterial in
        let material = SCNMaterial()
        material.diffuse.contents = color
        material.locksAmbientWithDiffuse = true
        return material
    }

    let boxGeometry = SCNBox(width: 0.12, height: 0.01, length: 0.07, chamferRadius: 0)
    boxGeometry.materials = sideMaterials

    let node = SCNNode(geometry: boxGeometry)
    node.transform = SCNMatrix4MakeRotation(-Float.pi / 2, 1, 0, 0)
    node.eulerAngles.x = .pi / 2

    return node
}

我还尝试在func渲染器(_渲染器:SCNSceneRenderer,didAdd节点:SCNNode,锚点:ARAnchor)中进行旋转

func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
    node.eulerAngles.x = .pi / 2
}

但这也没有帮助。

我成功使用下面的代码为旋转动画。

    let spin = CABasicAnimation(keyPath: "rotation")
    // Use from-to to explicitly make a full rotation around z
    spin.fromValue = NSValue(scnVector4: SCNVector4(x: 0, y: 0, z: 1, w: 0))
    spin.toValue = NSValue(scnVector4: SCNVector4(x: 0, y: 0, z: 1, w: Float(2 * Double.pi)))
    spin.duration = 3
    spin.repeatCount = 1
    node.addAnimation(spin, forKey: "rotation")

基于成功,我也尝试了(但失败了)

    node.rotation = SCNVector4(x: 5, y: 4, z: 3, w: 0)

有人知道如何在ARSCNViewDelegate的委托方法中旋转节点吗?

1 个答案:

答案 0 :(得分:1)

ARSession将对您要出售的节点进行定位和定向。最好在子节点上旋转到要出售的子节点。所以在func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode?

返回之前,您可以说:

let node = SCNNode(geometry: boxGeometry)
node.eulerAngles = SCNVector3(x: -Float.pi / 2, y: 0, z: 0)

let rootNode = SCNNode()
rootNode.addChildNode(node)
return rootNode