如何控制多个具有相同名称的精灵套件节点?

时间:2016-04-29 01:41:15

标签: ios swift sprite-kit

斯威夫特2 SpriteKit

所以我使用以下代码随机生成敌人,然后将它们移向播放器。但由于某种原因,只有第一个敌人向玩家移动,其余的什么都不做。我是新手,所以所有细节都会有所帮助。

在didmovetoview下:

        let wait = SKAction.waitForDuration(3, withRange: 2)
        let spawn = SKAction.runBlock {
            let Enemy = SKSpriteNode(imageNamed: "Enemy.png")
            Enemy.size.height = (70) //138
            Enemy.size.width = (49) //99
            Enemy.position = CGPointMake(CGRectGetWidth(self.frame) - 100 , CGRectGetHeight(self.frame) - 100)
            Enemy.physicsBody = SKPhysicsBody (rectangleOfSize: Enemy.size)
            Enemy.physicsBody!.dynamic = true
            Enemy.physicsBody!.allowsRotation = false
            Enemy.physicsBody!.friction = 0
            Enemy.physicsBody!.restitution = 0
            Enemy.physicsBody!.linearDamping = 1
            Enemy.physicsBody!.angularDamping = 1
            Enemy.name = "Enemy"
            Enemy.zPosition = 3
            self.addChild(Enemy)
            self.EnemyExists=true

        }
        let sequence = SKAction.sequence([wait, spawn])
        self.runAction(SKAction.repeatActionForever(sequence))

在更新功能下:

            let Enemy = childNodeWithName("Enemy") as! SKSpriteNode
            let Player = childNodeWithName("Player") as! SKSpriteNode

            if EnemySpeed == OriginalEnemySpeed {

                let impulseVector = CGVector(dx: (Player.position.x - Enemy.position.x)/200, dy: (Player.position.y - Enemy.position.y)/200)
                Enemy.physicsBody?.applyImpulse(impulseVector)
            }

            if Enemy.position.x + Enemy.size.width / 4 > size.width {
                Enemy.position.x = Enemy.size.width / 4

            }
            else if Enemy.position.x + Enemy.size.width / 4 < 0 {
                Enemy.position.x = size.width - Enemy.size.width / 4

            }

            if Enemy.position.y + Enemy.size.height / 4 > size.height {
                Enemy.position.y = Enemy.size.height / 4

            }
            else if Enemy.position.y + Enemy.size.height / 4 < 0 {
                Enemy.position.y = size.height - Enemy.size.height / 4

            }

            EnemySpeed-=1
            if EnemySpeed < 1 {
                EnemySpeed = OriginalEnemySpeed
            }

1 个答案:

答案 0 :(得分:3)

childNodeWithName("Enemy")只会在名为Enemy的场景中拾取第一个精灵。

你需要使用enumerateChildNodesWithName遍历所有精灵,称为敌人:

        enumerateChildNodesWithName("Enemy") {
            node, stop in
            let Enemy = node as! SKSpriteNode

            // Your enemy movement/update code here

        }

如果您的EnemySpeed变量应该引用您当前正在处理的精灵的速度,则必须对其进行一些操作,因为它只是一个实例变量而不是该精灵的属性。你可能想要使用Enemy.physicsBody.velocity,这是一个CGVector,所以要把它转换成你需要的速度:

enemySpeedX = enemy.physicsbody.velocity.dx
enemySpeedY = enemy.physicsbody.velocity.dy
enemySpeed = sqrt(enemySpeedX* enemySpeedX + enemySpeedY* enemySpeedY)

同时检查您的命名标准;大多数事情应该是驼峰式的,因此Enemy应为enemyOriginalEnemySpeed应为originalEnemySpeed等。