【问题标题】:Creating a Random Position for a Sprite in Swift在 Swift 中为 Sprite 创建一个随机位置
【发布时间】:2015-08-08 18:03:29
【问题描述】:

我有一个圆形精灵,我想将它移动到 iOS 设备屏幕范围内的随机位置。我试图在 Swift 中做到这一点,但我仍然是初学者,我什至不知道从哪里开始。有谁知道如何为精灵创建一个随机位置?提前谢谢!

-维尼

【问题讨论】:

    标签: xcode swift random position


    【解决方案1】:

    斯威夫特 3:

    func spawnRandomPosition() {
    
    let height = self.view!.frame.height
    let width = self.view!.frame.width
    
    let randomPosition = CGPoint(x:CGFloat(arc4random()).truncatingRemainder(dividingBy: height),
                                     y: CGFloat(arc4random()).truncatingRemainder(dividingBy: width))
    
    let sprite = SKSpriteNode()
    sprite.position = randomPosition
     }
    

    【讨论】:

      【解决方案2】:

      假设您从场景类中调用代码:

      func spawnAtRandomPosition() {
          let height = self.view!.frame.height
          let width = self.view!.frame.width
      
          let randomPosition = CGPointMake(CGFloat(arc4random()) % height, CGFloat(arc4random()) % width)
      
          let sprite = SKSpriteNode()
          sprite.position = randomPosition
      }
      

      【讨论】:

        【解决方案3】:

        斯威夫特 3:

        let randomPosition = CGPoint( x:CGFloat( arc4random_uniform( UInt32( floor( width  ) ) ) ),
                                      y:CGFloat( arc4random_uniform( UInt32( floor( height ) ) ) )
                                      )
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-27
          • 1970-01-01
          相关资源
          最近更新 更多