0

我一直在努力让它工作 3 天。对于我的项目,我需要在用 Swift for iOS 编写的 AR 应用程序中将变化的值显示为 3d 文本。

我已经发现:我可以使用以下代码在某个位置生成 3d 静态文本。我可以将它放在 ViewController 的 ViewDidLoad 方法中,以便在启动时加载一次。

let text = SCNText(string: "Let's begin!", extrusionDepth: 1)

//Create material
let material = SCNMaterial()
material.diffuse.contents = UIColor.green
text.materials = [material]

//Create Node object
let textNode = SCNNode()
textNode.scale = SCNVector3(x:0.004,y:0.004,z:0.004)
textNode.geometry = text
textNode.position = SCNVector3(x: 0, y:0.02, z: -0.5)

sceneView.scene.rootNode.addChildNode(textNode)

现在我的问题是我不能让它定期更改并说计数到 10000。

我尝试了很多想法,但没有一个显示数字在增加。

更新:我在创建节点后无法删除它。我也不知道什么时候必须删除它。

我收到错误的访问代码=1 错误。问题似乎在于查找和删除节点,因为如果我评论应用程序启动的行。它可能与访问权限有关。

这是我的功能:

func updateSCNText2 (incomingInt: Int) {

    // create new text
    let text = SCNText(string: String(incomingInt), extrusionDepth: 1)
    //  create material
    let material = SCNMaterial()
    material.diffuse.contents = UIColor.green
    text.materials = [material]

    //Create Node object
    let textNode = SCNNode()
    textNode.name = "textNodeName"
    textNode.scale = SCNVector3(x:0.004,y:0.004,z:0.004)
    textNode.geometry = text
    textNode.position = SCNVector3(x: 0, y:0.02, z: -0.5)

    //  add new node to root node
    sceneView.scene.rootNode.addChildNode(textNode)

    //  find & remove previous node (childNodeWithName)
    sceneView.scene.rootNode.childNode(withName: "textNodeName", recursively: false)?.removeFromParentNode()

}

我在哪里调用函数:

var k = 0

func renderer(_ renderer: SCNSceneRenderer,
              updateAtTime time: TimeInterval) {

    print(k)
    updateSCNText2(incomingInt:  k)
    k = k+1
}

非常感谢您抽出宝贵的时间!

4

1 回答 1

0

Best way to do this is using NSTimer

Firstly, set textNode & a counter var at the top of your ViewController class

var textNode: SCNNode!

var counter = 0

inside of viewDidLoad add the NSTimer call:

var timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)

leave you original textNode creation method in ViewDidLoad except textNode is now var

this is the update function

@objc func update() {

    counter += 1

    // remove the old textNode

    textNode.removeFromParentNode()

        // create new text
        let text = SCNText(string: String(counter), extrusionDepth: 1)
        //  create material
        let material = SCNMaterial()
        material.diffuse.contents = UIColor.green
        text.materials = [material]

        //Create Node object
    textNode = SCNNode()
    textNode.scale = SCNVector3(x:0.004,y:0.004,z:0.004)
    textNode.geometry = text
    textNode.position = SCNVector3(x: 0, y:0.02, z: -0.5)

    //  add new node to root node
    self.sceneView.scene.rootNode.addChildNode(textNode)

}

Note: this code works, just tested it out in a playground. Can provide if needed.

于 2018-01-03T22:21:15.717 回答