我正在创建一个游戏,并且我一直在为使用操纵杆链接的子弹生成方法获取此错误。我想在操纵杆处于活动状态时重复生成项目符号节点。这是我如何创建一个射击方法
class GameScene: SKScene, SKPhysicsContactDelegate {
let bullet1 = SKSpriteNode(imageNamed: "bullet.png")
override func didMoveToView(view: SKView) {
if fireWeapon == true {
NSTimer.scheduledTimerWithTimeInterval(0.25, target: self,
selector: Selector ("spawnBullet1"), userInfo: nil, repeats: true)
}
}
func spawnBullet1(){
self.addChild(bullet1)
bullet1.position = CGPoint (x: hero.position.x , y:hero.position.y)
bullet1.xScale = 0.5
bullet1.yScale = 0.5
bullet1.physicsBody = SKPhysicsBody(rectangleOfSize: bullet1.size)
bullet1.physicsBody?.categoryBitMask = PhysicsCategory.bullet1
bullet1.physicsBody?.contactTestBitMask = PhysicsCategory.enemy1
bullet1.physicsBody?.affectedByGravity = false
bullet1.physicsBody?.dynamic = false
}
override func touchesBegan(touches: Set<UITouch>, withEvent
event:UIEvent?) {
for touch in touches {
let location = touch.locationInNode(self)
let node = nodeAtPoint(location)
if (CGRectContainsPoint(joystick.frame, location)) {
stickActive = true
if stickActive == true {
fireWeapon = true
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event:
UIEvent?) {
fireWeapon = false
}
第一个子弹按计划启动并且效果很好但是,每次第二个子弹启动应用程序崩溃时我都会收到此错误&#34;尝试添加已经拥有父级&#34;的SKNode。谁能告诉我一种替代方法
答案 0 :(得分:1)
您的问题正如错误所说的那样,您需要首先从其父级中删除子弹,然后再将其添加,或者在bullet1
函数中使spawnBullet
成为本地属性,以便每次都你调用该函数创建一个新子弹并将其作为子项添加到场景中,而不是尝试重新添加相同的子弹。