gpt4 book ai didi

ios - 不能在子类中运行 SKAction.runBlock

转载 作者:搜寻专家 更新时间:2023-11-01 06:40:29 24 4
gpt4 key购买 nike

我是 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 {

}

最佳答案

正如 crashoverride777 所说,您在 touchesBegan 中创建的原始 Bunny 永远不会添加到场景中。如果它不是场景的一部分,它永远不会运行您正在设置的任何操作。

var bun = Bunny()
self.addChild(bun)
bun.spawnBunnies()

此外,在 spawnBunnies 中,您将新生成的 Bunny 添加为生成它的 Bunny 的子项。这只兔子从场景中移除,因此新生成的兔子(它的 child )也被移除。

self.addChild(bunny) 应该是 parent?.addChild(bunny)。它可能还需要移动到 bunny.runAction(moveAndRemove) 行之上。

关于ios - 不能在子类中运行 SKAction.runBlock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36049649/

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