我是Swift的新手,但我遇到了类和继承问题。我有一个名为Bunny的类,它包含一些代码,包括SKAction。当我将Bunny中找到的代码放入我的GameScene类时,它运行正常,但是,当我尝试运行它时,当它在Bunny类中时,从我的GameScene类中它不起作用。
这是Bunny班:
import SpriteKit
class Bunny : SKSpriteNode {
var bunny = SKSpriteNode()
var moveAndRemove = SKAction()
var textureAtlas = SKTextureAtlas()
var textureArray = [SKTexture]()
func spawnBunnies() {
let spawn = SKAction.runBlock({
() in
self.spawnBunny()
print("CALLEDBunniesSpawned") // THIS PART IS NOT GETTING CALLED
})
let delay = SKAction.waitForDuration(3)
let spawnDelay = SKAction.sequence([spawn, delay])
let spawnDelayForever = SKAction.repeatActionForever(spawnDelay)
self.runAction(spawnDelayForever)
let distance = CGFloat(self.frame.width + bunny.frame.width)
let movePipes = SKAction.moveByX(-distance - 200, y: 0, duration: NSTimeInterval(0.009 * distance)) // Speed up pipes
let removePipes = SKAction.removeFromParent()
moveAndRemove = SKAction.sequence([movePipes, removePipes])
print("BunniesSpawned") // THIS PART HERE RUNS
}
func spawnBunny() { // I NEED TO TRIGGER THIS PART VIA THE SPAWN = SKAction.runBlock
print("BunniesSpawned2")
let randomYGen = CGFloat(arc4random_uniform(UInt32(self.frame.height - 80)))
textureAtlas = SKTextureAtlas(named: "Bunnies")
for i in 1...textureAtlas.textureNames.count {
var name = "Bunny\(i).png"
textureArray.append(SKTexture(imageNamed: name))
}
bunny = SKSpriteNode(imageNamed: textureAtlas.textureNames[5] as! String)
bunny.position = CGPoint(x: self.frame.width + bunny.frame.width / 2, y: randomYGen)
bunny.setScale(0.5)
bunny.runAction(moveAndRemove)
self.addChild(bunny)
bunny.runAction(SKAction.repeatActionForever(SKAction.animateWithTextures(textureArray, timePerFrame: 0.1)))
}
}
这是我的GameScene课程,我试图从Bunny调用该函数:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
if gameStarted == false {
gameStarted = true
var bun = Bunny()
bun.spawnBunnies()
} else {
}
答案 0 :(得分:2)
正如crashoverride777所说,您在Bunny
中创建的原始touchesBegan
永远不会添加到场景中。如果它不是场景的一部分,它将永远不会运行您正在设置的任何操作。
var bun = Bunny()
self.addChild(bun)
bun.spawnBunnies()
此外,在spawnBunnies
中,您要将新生成的Bunny
添加为正在生成它的Bunny
的子项。这个兔子被从场景中移除,所以新生的兔子(它的孩子)也被移走了。
self.addChild(bunny)
应为parent?.addChild(bunny)
。它可能还需要移到bunny.runAction(moveAndRemove)
行之上。
答案 1 :(得分:1)
除非我遗漏了一些东西,否则你不会将Bunny子类添加到场景中。
试试这个
var bun = Bunny()
addChild(bun)
bun.spawnBunnies()