swift - SpriteKit SKSprite节点

标签 swift variables sprite-kit

func repulseFire() {
if let zombieGreen =  self.childNode(withName: "zombie") as? SKSpriteNode {
    self.enumerateChildNodes(withName: "repulse") {
        node, stop in
        if let repulse = node as? SKSpriteNode {
        if let action = zombieGreen.action(forKey: "zombieAction") {
                action.speed = 0
                func run() {
                    action.speed = 1
                }
                var dx = CGFloat(zombieGreen.position.x - repulse.position.x)
                var dy = CGFloat(zombieGreen.position.y - repulse.position.y)
                let magnitude = sqrt(dx * dx + dy * dy)
                dx /= magnitude
                dy /= magnitude
                let vector = CGVector(dx: 25.0 * dx, dy: 25.0 * dy)
                func applyImpulse() {
                zombieGreen.physicsBody?.applyImpulse(vector)
                }
                zombieGreen.run(SKAction.sequence([SKAction.run(applyImpulse), SKAction.wait(forDuration: 0.2), SKAction.run(run)]))
            }

            }
        }
    }
}

调用此函数时,我正试图击退僵尸。唯一的问题是在某些时间点现场有不止一只僵尸,并且脉冲仅适用于屏幕上先于其他僵尸生成的僵尸。我怎样才能让所有的僵尸都受到影响?我认为这与“if let zombieGreen = self.childNode(withName: "zombie") as?SKSpriteNode”这一行有关

最佳答案

将僵尸添加到场景时,应考虑使用数组来存储它们。这比枚举场景更快,并为您提供更大的灵 active 。

// create an array of spriteNodes
    var zombieArray:[SKSpriteNode]

    //add zombies to array when you add them to scene
    zombieArray.append(zombieGreen)

    //check if any zombies are in the scene
    if zombieArray.count > 0{
        .....
    }

    //Do something with all the zombies in the array - your main question.
    for zombie in zombieArray{

        .....
        zombie.physicsBody?.applyImpulse(vector)
    }

    // remove zombie from array
    zombieArray.remove(at: zombieArray.index(of: theZombieYouWantToRemove))

关于swift - SpriteKit SKSprite节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45045758/

相关文章:

ios - 使用执行选择器但带有参数创建 SKAction

ios - 从 SMS 打开应用程序,如地址打开计划或 Doctolib

ios - 在 iOS map 中显示多个注释

javascript - 函数中的jquery变量

ios - 取消点击手势识别器

xcode - 调用 shadowCastBitMask= 时出现奇怪的屏幕大小调整错误

ios - Swift - 如何获得视频维度?

swift - SKPhysicsContact 主体,无法更改属性

c++ - 静态变量指针?

php - 如何在 PHP 中使用 for 循环打印 $title1 $title2 $title3...