Ios Can’;t在子类中运行SKAction.runBlock
我是Swift新手,但我在类和继承方面遇到了麻烦。我有一个名为Bunny的类,它包含一些代码,包括一个SKAction。当我将在Bunny中找到的代码放入GameSecene类中时,它工作正常,但是当我尝试运行它时,当它在Bunny类中时,从GameSecene类中它不工作 这是兔子课:Ios Can’;t在子类中运行SKAction.runBlock,ios,swift,sprite-kit,Ios,Swift,Sprite Kit,我是Swift新手,但我在类和继承方面遇到了麻烦。我有一个名为Bunny的类,它包含一些代码,包括一个SKAction。当我将在Bunny中找到的代码放入GameSecene类中时,它工作正常,但是当我尝试运行它时,当它在Bunny类中时,从GameSecene类中它不工作 这是兔子课: import SpriteKit class Bunny : SKSpriteNode { var bunny = SKSpriteNode() var moveAndRemove = SKA
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)))
}
}
这是我的GameSecene类,我试图从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 {
}
覆盖函数触摸开始(触摸:设置,withEvent事件:UIEvent?){
/*当触摸开始时调用*/
如果gameStarted==false{
gameStarted=true
var bun=Bunny()
小兔子
}否则{
}
正如crashoverride777所说,您在ToucheSBegind
中创建的原始兔子从来不会添加到场景中。如果它不是场景的一部分,它将永远不会运行您正在设置的任何动作
var bun = Bunny()
self.addChild(bun)
bun.spawnBunnies()
此外,在sprownbunnies
中,您将新生成的Bunny
添加为正在生成它的Bunny
的子对象。该兔子将从场景中移除,因此新生成的兔子(即它的子对象)也将被移除
self.addChild(bunny)
应该是parent?.addChild(bunny)
。它可能还需要移动到bunny.runAction(moveAndRemove)
行的上方,除非我缺少一些东西,否则您不能将bunny子类添加到场景中
试试这个
var bun = Bunny()
addChild(bun)
bun.spawnBunnies()