SKSpriteNode加了一次,莫名其妙出现了,加了六次

SKSpriteNode was added once, but it appeared a baffling, six times

我只在我的动作块中添加了一次 SKSpriteNode,bullet,但不知何故它导致六个不同的节点出现在我的模拟器中。我对我的模拟器中如何出现六个节点感到非常困惑。为什么会这样?这可能是 Xcode 中的错误吗?我删除了代码中不相关的部分,因此您不必通读所有代码。提前致谢!

class MyScene: SKScene {
    var score = 0
    var playerHealth = 100
    var spaceShipHealth = 1000
    var shooterAnimation = [SKTexture]()
    var numberOfEnemies = 5


    override func didMoveToView(view: SKView) {
        //After load, send all of the images in the atlas to the SkTexture
        let shooter = self.childNodeWithName("shooter1")
        shooter?.zPosition = 1

        let shooterAtlas = SKTextureAtlas(named: "shooter")
        for image in 1...shooterAtlas.textureNames.count {
            let imgName = String(format: "shooter%01d", image)
            shooterAnimation += [shooterAtlas.textureNamed(imgName)]
            let skActionBlock = SKAction.sequence([SKAction.runBlock({
                    let bullet = self.createSpaceshipBulletNode()
                    self.addChild(bullet)
                    bullet.physicsBody?.applyImpulse(CGVectorMake(-100, 0))
                }),SKAction.waitForDuration(3.0)])
            self.runAction(SKAction.repeatAction(skActionBlock, count: numberOfEnemies))
        }
        self.physicsWorld.gravity = CGVectorMake(0, 0.2)

        let bgImage = SKSpriteNode(imageNamed: "spaceBackground.jpeg")
        let frameSize = self.frame.size
        bgImage.size = frameSize
        bgImage.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
        bgImage.zPosition = 0
        self.addChild(bgImage)
    }

    func createSpaceshipBulletNode() -> SKSpriteNode{
        let spaceShip = self.childNodeWithName("Spaceship")
        let bulletX:CGFloat! = (spaceShip?.position.x)! - 200
        let bulletY:CGFloat! = spaceShip?.position.y
        let sBullet = SKSpriteNode(imageNamed: "bullet.png")
        sBullet.position = CGPointMake(bulletX, bulletY)
        sBullet.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(50, 50))
        return sBullet
    }
}

运行您的 createSpaceshipBulletNode 的操作块重复 numberOfEnemies 次,并且该调用在从 1 运行到 shooterAtlas.textureNames.count 的 for 循环中。要么你的 for 循环是 运行 多次,要么你有 6 个敌人。也许你的意思是在循环之外添加项目符号,并且只在循环中设置纹理。

for image in 1...shooterAtlas.textureNames.count {
        let imgName = String(format: "shooter%01d", image)
        shooterAnimation += [shooterAtlas.textureNamed(imgName)]
}
let skActionBlock = SKAction.sequence([SKAction.runBlock({
    let bullet = self.createSpaceshipBulletNode()
    self.addChild(bullet)
    bullet.physicsBody?.applyImpulse(CGVectorMake(-100, 0))
}),SKAction.waitForDuration(3.0)])

self.runAction(SKAction.repeatAction(skActionBlock, count: numberOfEnemies))
self.physicsWorld.gravity = CGVectorMake(0, 0.2)