【问题标题】:Getting a random CGFloat value from an array?从数组中获取随机 CGFloat 值?
【发布时间】:2016-02-01 10:10:45
【问题描述】:

我有一个包含 CGFloat 值的数组,我试图弄清楚如何通过这个数组进行随机化以获得随机 x 坐标:

let xAxisSpawnLocations: [CGFloat] = [screenWidth + 150, screenWidth + 100, screenWidth + 50 , screenWidth - 50, screenWidth - 100, screenWidth - 150]  

因为我必须将它们放入将在地图上定位对象的代码行中。

obstacle.position = CGPoint(x: ARRAY VALUE HERE, y: yAxisSpawnLocations[0])

我尝试查找如何通过数组随机化,但它仅适用于 Int32 值。

请提供一些关于如何执行此操作的示例。

以下是完整代码供您参考:

let xAxisSpawnLocations: [CGFloat] = [screenWidth + 150, screenWidth + 100, screenWidth + 50 , screenWidth - 50, screenWidth - 100, screenWidth - 150]
let yAxisSpawnLocations: [CGFloat] = [0]                          

        for xLocation in xAxisSpawnLocations {

            for (var i = 0; i < Int(numberOfObjectsInLevel); i++) {


            let obstacle:Object = Object()

            obstacle.theType = LevelType.road


            obstacle.createObject()
            addChild(obstacle)



            obstacle.position = CGPoint(x: xLocation, y: yAxisSpawnLocations[0])
            obstacle.zPosition = 9000
           // addChild(greenFrog)
        }
      }
    }

xLocation 需要被随机化器替换

【问题讨论】:

标签: arrays swift random cgfloat


【解决方案1】:

虽然您的数组可能存储CGFloat 值,但数组索引仍将是整数。数组始终具有基于整数的索引,无论它们存储什么。

您只想生成一个介于 0 和数组长度之间的随机整数并访问该索引处的元素:

let randx = xAxisSpawnLocations[Int(arc4random_uniform(UInt32(xAxisSpawnLocations.count)))]
obstacle.position = CGPoint(x: randx, y: yAxisSpawnLocations[0])

【讨论】:

  • 我最大的菜鸟错误我忘记了所有关于索引的事情。 xD 但是是的,这确实解决了我的问题,谢谢。
猜你喜欢
  • 1970-01-01
  • 2018-06-19
  • 2022-10-08
  • 2010-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多