gpt4 book ai didi

ios - SpriteKit-随机生成

转载 作者:行者123 更新时间:2023-12-01 18:39:57 25 4
gpt4 key购买 nike

我试图在X轴上随机生成一个对象,但它仅在中心生成。

以下是我关于衍生产品的报价。缺少了什么?

//随机函数

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

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

//生成猫功能
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)

}

最佳答案

使用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宽度为0

关于ios - SpriteKit-随机生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44830190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com