我在SpriteKit游戏中有6个敌人精灵。我想要访问所有这些像“敌人”,以使它们以随机顺序出现在场景中。我试着这样做:
class GameScene: SKScene {
var redBox = SKSpriteNode(imageNamed: "redBox")
var greenBox = SKSpriteNode(imageNamed: "greenBox")
var blueBox = SKSpriteNode(imageNamed: "blueBox")
var magentaBox = SKSpriteNode(imageNamed: "magentaBox")
var cyanBox = SKSpriteNode(imageNamed: "cyanBox")
var yellowBox = SKSpriteNode(imageNamed: "yellowBox")
func randomBox() -> SKSpriteNode {
let boxes = [redBox, greenBox, blueBox, magentaBox, cyanBox, yellowBox]
let count = boxes.count
var randomOne = Int(arc4random_uniform(UInt32(count)))
var randomBox = boxes[randomOne]
return randomBox
}
var oneBox: SKSpriteNode = randomBox()
}
但是在oneBox中Xcode给了我一个错误并说“在调用中缺少参数#1”。
如何以正确的方式选择随机节点?
编辑:导致该错误的代码:
class GameScene: SKScene {
//boxes
var redBox = SKSpriteNode(imageNamed: "redBox")
var greenBox = SKSpriteNode(imageNamed: "greenBox")
var blueBox = SKSpriteNode(imageNamed: "blueBox")
var magentaBox = SKSpriteNode(imageNamed: "magentaBox")
var cyanBox = SKSpriteNode(imageNamed: "cyanBox")
var yellowBox = SKSpriteNode(imageNamed: "yellowBox")
var oneBox:SKSpriteNode!
func randomBox() -> SKSpriteNode {
let boxes = [redBox, greenBox, blueBox, magentaBox, cyanBox, yellowBox]
let count = boxes.count
var randomOne = Int(arc4random_uniform(UInt32(count)))
var randomBox = boxes[randomOne]
return randomBox
}
//random for Y
func random() -> CGFloat {
return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}
func random(#min: CGFloat, max: CGFloat) -> CGFloat {
return random() * (max - min) + min
}
override func didMoveToView(view: SKView) {
/* Setup your scene here */
var oneBox: SKSpriteNode = randomBox()
func addUpperBoxes() {
let middleY = random(min: size.height/2, max: size.height - size.height/3)
oneBox.position = CGPoint(x: size.width + oneBox.size.width/2, y: middleY)
addChild(oneBox)
let middleDuration = random(min: CGFloat(1.5), max: CGFloat(2.5))
let middleMove = SKAction.moveTo(CGPoint(x: -oneBox.size.width/2, y: middleY), duration: NSTimeInterval(middleDuration))
let middleMoveDone = SKAction.removeFromParent()
oneBox.runAction(SKAction.sequence([middleMove, middleMoveDone]))
}
runAction(SKAction.repeatActionForever(
SKAction.sequence([
SKAction.runBlock(addUpperBoxes),
SKAction.waitForDuration(0.5)
])
))
}