SpriteKit-随机化产卵

时间:2017-06-29 16:09:00

标签: ios sprite-kit

我正在尝试在X轴上随机生成一个对象,但它只在中心产生。

下面是关于产卵的引用。有什么遗漏?

// random func

func random() -> CGFloat {
    return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}

func random(min: CGFloat, max: CGFloat) -> CGFloat {
    return random() * (max - min) + min
}

// spawn cat func

func spawnCat(){

    let randomXStart = random(min: gameArea.minX, max: gameArea.maxX)
    let randomXEnd  = random(min: gameArea.minX, max: gameArea.maxX)

    let startPoint = CGPoint(x: randomXStart, y:self.size.height * 1.2)
    let endPoint = CGPoint(x: randomXEnd, y: -self.size.height * 1)

    let cat = SKSpriteNode(imageNamed: "before right")
    cat.setScale(0.3)
    cat.position = startPoint
    cat.zPosition = 1
    self.addChild(cat)

    let moveCat = SKAction.move(to: endPoint, duration: 2)
    let deleteCat = SKAction.removeFromParent()
    let catSequence = SKAction.sequence([moveCat, deleteCat])
    cat.run(catSequence)

}

1 个答案:

答案 0 :(得分:3)

使用arc4random_uniform来获得您想要的结果

func spawnCat(){



    let randomXStart = CGFloat(arc4random_uniform(UInt32(gameArea.maxX - gameArea.minX))) + CGFloat(gameArea.minX)
    let randomXEnd   = CGFloat(arc4random_uniform(UInt32(gameArea.maxX - gameArea.minX))) + CGFloat(gameArea.minX)
    let startPoint = CGPoint(x: randomXStart, y:self.size.height * 1.2)
    let endPoint = CGPoint(x: randomXEnd, y: -self.size.height * 1)

    let cat = SKSpriteNode(imageNamed: "before right")
    cat.setScale(0.3)
    cat.position = startPoint
    cat.zPosition = 1
    self.addChild(cat)

    let moveCat = SKAction.move(to: endPoint, duration: 2)
    let deleteCat = SKAction.removeFromParent()
    let catSequence = SKAction.sequence([moveCat, deleteCat])
    cat.run(catSequence)

}

如果您使用此代码获得0,则表示您的gameArea width为0