import SpriteKit
var counter:Int
var randX = Int(arc4random_uniform(255))
var randY = Int(arc4random_uniform(425))
var coin:SKSpriteNode?
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
//...
for var index = 0; index < 3; ++index {
print("index is \(index)")
coin = SKSpriteNode(fileNamed: "gargar")
coin.frame = CGRectMake(randX, randY, coin.frame.size.width,
coin.frame.size.height)
self.addChild(coin)
}
}
好吧,我已经有了循环。我有x,y的随机数,所以希望它会保持在CGRectMake范围内吗?我已经找到了与执行相关的问题/答案,但也许它很简单,没有人遇到过它?请指教。我非常感谢并付出代价。
创造性, 门萨
答案 0 :(得分:3)
您想要设置精灵的位置,而不是帧。
coin = SKSpriteNode(fileNamed: "gargar")
coin.position = CGPoint(x: randX, y: randY)
self.addChild(coin)
如果您尝试从图像创建节点,您实际上将使用
coin = SKSpriteNode(imageNamed: "gargar")
fileNamed
用于加载.sks
个文件,而不是图片。
请记住,randX和randY的值在整个循环中不会发生变化。您目前正在同一位置添加3个精灵。如果您希望它们全部位于不同的位置,请将循环内部的随机点生成移动。
答案 1 :(得分:0)
//created random float using arc4random()
func random() -> CGFloat {
return CGFloat(Float(arc4random()) / 0xFFFFFFFF) }
//manipulate that random f. to only return values btwn 0 and 1
func random2(min min: CGFloat, max: CGFloat) -> CGFloat {
return random() * (max - min) + min }
//iterate loop 50x placing enemy position randomly
for (counter = 1; counter <= 50; counter++) {
//add objects to scene
func spawnEnemy() {
let enemy = SKSpriteNode(imageNamed: "gargar")
enemy.position = CGPoint(x: frame.size.width * random2(min: 0, max: 1), y: frame.size.height * random2(min: 0, max: 1))
addChild(enemy)
}
//run SKAction to limit spawnEnemy placement to 1x
runAction(SKAction.sequence([SKAction.runBlock(spawnEnemy)]))