Sam Sam - 3 months ago 14
Swift Question

Managing GameScenes update method and referencing changing instance properties within other classes

I'm making my first game in Swift and I'm trying to get a

SKSpriteNode
subclass instance (
trailingSprite
) to follow or "trail" another
SKSpriteNode
subclass (
User
) that the user controls. I was able to achieve this by making a
move(aUser:User)
method within the
trailingSprite
class that applies a velocity vector to to the trailing body thats the difference of the two
postions
I then call this method inside of GameScenes
Update
function. However, this
trailingSprite
isn't always on screen and can spawn at random times in differing quantities. Is there a more effective way of retrieving "live" or updated positions of the
User
instance within each
trailingSprite
instance instead of having to call a move method for each one inside of Update (which ultimately wont work)? I also tried passing the
User
instance by reference but this still didn't work as the velocity vector never updated from the original positions. Any help would be awesome!

Answer

Inside the update method you should be able to call a move method on every trailingSprite in your scene by finding all the nodes with the corresponding name.

self.enumerateChildNodes(withName: "trailingSprite", using: { node, _ in
    if let trailingSprite = node as? TrailingSprite {
        trailingSprite.move(aUser: user)
    }
})

This would require that you set the name property on your TrailingSprite class:

self.name = "trailingSprite"
Comments