B.Toaster
B.Toaster

Reputation: 169

SpriteKit SKSpriteNode

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)]))
            }

            }
        }
    }
}

I am trying to hit back the zombies when this function is called. The only issue is that there are more than one zombie on the scene at some points in time and the impulse is only applied to the zombie that spawned before the others on the screen. How can I make it so that all the zombies are affected? I think it has to do with the line "if let zombieGreen = self.childNode(withName: "zombie") as? SKSpriteNode"

Upvotes: 0

Views: 137

Answers (2)

Simone Pistecchia
Simone Pistecchia

Reputation: 2832

All zombies affected by All repulse node in scene

func repulseFire() {
    self.enumerateChildNodes(withName: "zombie") {
            zombieGreen, stop in {

            self.enumerateChildNodes(withName: "repulse") {
                node, stop in
                //etc

All zombies affected by ONE repulse node in scene

func repulseFire() {
    self.enumerateChildNodes(withName: "zombie") {
            node, stop in {
        if let repulseNode =  self.childNode(withName: "repulse") {
            //etc

Upvotes: 0

Magnus Ewerlöf
Magnus Ewerlöf

Reputation: 541

You should consider using an Array to store the zombie when you add them to the scene. This is faster then enumerating the scene and gives you more flexibility.

// 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))

Upvotes: 1

Related Questions