如何创建随机节点以随机出现,但它们不与场景中的当前节点重叠?

时间:2016-10-27 20:11:48

标签: sprite-kit swift3

我对iOS Swift和精灵套件相当陌生,但我目前正在开发一款游戏,我想让项目(SKSpriteNode s)随机出现,当它们出现时,它们不会重叠使用游戏场景中的现有节点。

下面是我的代码,用于生成随机节点和指定的范围时间间隔,以显示在场景宽度/高度上。但是,我没有合并允许它们重叠的代码或者在场景中的其他当前节点之上。

override func didMove(to view: SKView) {

    let wait = SKAction.wait(forDuration: 10, withRange: 5)
    let spawn = SKAction.run {
        self.randomFood()
    }

    let spawning = SKAction.sequence([wait,spawn])    
    self.run(SKAction.repeat((spawning), count: 5))
}

func randomFood() {
    //supposed to pick random point within the screen width
    let xPos = randomBetweenNumbers(firstNum: 0, secondNum: frame.width )

    let foodNode = SKSpriteNode(imageNamed: "burgerFood") //create a new food item each time
    foodNode.position = CGPoint(x: xPos, y: self.frame.size.height/2)
    foodNode.setScale(0.10)
    foodNode.physicsBody = SKPhysicsBody(circleOfRadius: foodNode.size.width/2)
    foodNode.zPosition = 10
    foodNode.alpha = 1
    foodNode.physicsBody?.affectedByGravity = false
    foodNode.physicsBody?.categoryBitMask = 0
    foodNode.physicsBody?.contactTestBitMask = 0
    addChild(foodNode)
}

func randomBetweenNumbers(firstNum: CGFloat, secondNum: CGFloat) -> CGFloat {
    return CGFloat(arc4random()) / CGFloat(UINT32_MAX) * abs(firstNum - secondNum) + min(firstNum, secondNum)
}

0 个答案:

没有答案