我为这个令人困惑的问题标题道歉,但我不太确定如何说出我的问题。我的最终目标是在创建后的一段时间内删除SKSpriteNode。然而,有一个小的复杂性。使用以下代码
func remove() {
laser.removeFromParent()
}
runAction(
SKAction.sequence([
SKAction.waitForDuration(5.0),
SKAction.runBlock(remove)
])
)
我能够删除名为'laser'的SKSpriteNode。当我调用我的函数一次,fireLasers(),一切运行平稳,激光在5秒后消失。问题是我在5秒钟内调用它两次。当发生这种情况时,第一个激光将无限期地粘住,第二个激光会比预期更早消失。我明白为什么会这样,但想知道是否有办法绕过它。这是GameScene的代码,它创建了世界,背景图像,玩家Sprite,并定义了fireLasers函数。 ViewController中有很多东西可以处理sprite的速度和方向,但我希望这足以找到解决方案。
import SpriteKit
class GameScene: SKScene {
var player = SKSpriteNode()
var world = SKShapeNode()
var worldTexture = SKSpriteNode()
var laser = SKShapeNode()
override func didMoveToView(view: SKView) {
self.anchorPoint = CGPointMake(0.5, 0.5)
self.size = CGSizeMake(view.bounds.size.width, view.bounds.size.height)
// Add world
world = SKShapeNode(rectOfSize: CGSizeMake(7000, 7000))
world.physicsBody = SKPhysicsBody(edgeLoopFromPath: world.path!)
world.fillColor = SKColor.blackColor()
self.addChild(world)
// Add Background Image
worldTexture = SKSpriteNode(imageNamed: "grid")
worldTexture.size = CGSize(width: 7000, height: 7000)
world.addChild(worldTexture)
// Add player
player = SKSpriteNode(imageNamed: "Spaceship")
player.size = CGSize(width: 50, height: 50)
player.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: 50, height: 50))
player.physicsBody?.affectedByGravity = false
player.physicsBody?.dynamic = true
world.addChild(player)
}
override func update(currentTime: CFTimeInterval) {
world.position.x = -player.position.x
world.position.y = -player.position.y
}
func fireLasers() {
laser = SKShapeNode(rectOfSize: CGSizeMake(10, 50))
laser.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: 10, height: 50))
laser.position.x = player.position.x
laser.position.y = player.position.y + CGFloat(50)
laser.fillColor = SKColor.redColor()
laser.physicsBody?.dynamic = true
laser.physicsBody?.affectedByGravity = false
world.addChild(laser)
func remove() {
laser.removeFromParent()
}
runAction(
SKAction.sequence([
SKAction.waitForDuration(5.0),
SKAction.runBlock(remove)
])
)
}
}
答案 0 :(得分:2)
不是保留对激光的引用(正如你所注意到的那样,会强迫你一次只有一个),为什么不在创建的激光节点上自行动作呢?这样您就可以使用方便的SKAction
类方法removeFromParent()
:
let newLaser = makeNewLaser()
let laserAction = SKAction.sequence([SKAction.waitForDuration(5), SKAction.removeFromParent()])
newLaser.runAction(laserAction)