在AR场景视图中随机将对象放置在10米半径范围内

时间:2018-03-08 11:31:40

标签: swift scenekit arkit

我希望能够在设定半径(5-10米)内随机放置一个物体。这个想法是用户将走动,最终对象将进入视野。

1 个答案:

答案 0 :(得分:0)

以下是使用@ Coeur的randomDistance函数的示例:

  /// Spawns 5 Nodes At Random Distances Away From The Camera
  func spwanRandomNodes(){

    //1. Create An Array Of Colours
    var colourArray: [UIColor] = [.red, .green, .yellow, .cyan, .white]

    //2. Create 5 Different Spheres With A Random Color & Position
    for i in 0...4{

        let nodeHolder = SCNNode()
        let nodeGeometry = SCNSphere(radius: 0.2)
        nodeGeometry.firstMaterial?.diffuse.contents = colourArray[i]
        nodeHolder.geometry = nodeGeometry

        //3. Create A Random Distance From 5 To 10 (Cœur's Answer)
        let randomDistanceFrom5To10 = Float(arc4random()) / Float(UInt32.max) * 5 + 5

        //4. Add The Node To The Scene Root
        augmentedRealityView?.scene.rootNode.addChildNode(nodeHolder)

        //5. Generate The Random SCNVector3

        /* Here I Have Added An XSpacer Simply For Testing */
        let xSpacer = Float(0.3 * Float(i))

        let randomVector =  SCNVector3 (xSpacer, 0, -(randomDistanceFrom5To10))

        //6. Set THe Nodes Positon
        nodeHolder.position = randomVector
    }

}