swiftsprite-kitskspritenodeskphysicsbody

Are sprites automatically removed?


I'm currently trying to code some falling stars in my game, and they seem to disappear once they move out of the screen. But I'm not sure if swift is actually automatically deleting for me, or if they're still lingering around.

I'm starting them at the top of the screen and using physicsBody to use gravity to bring them down.

star.physicsBody = SKPhysicsBody(rectangleOf: star.size)

I know apple documentation says "Later, if the sprite is removed from the scene or is no longer visible, SpriteKit can delete the texture data if it needs that memory for other purposes."

https://developer.apple.com/documentation/spritekit/skspritenode/getting_started_with_sprite_nodes

but I find that kind of vague and just want some confirmation that because I can't see my star sprite anymore on my screen, I can also assume that it's being removed.

(and not just clumping up somewhere off screen)


Solution

  • No - it's not automatically removed.

    By 'removed from scene' the SK documentation doesn't mean that if you can't see it anymore, it means that the 'RemoveFrom...' method was called on the sprite in question.

    If the sprite isn't visible, then the game engine won't draw it and could optimise memory by removing it's texture, but the sprite is still being tracked and colliding and bouncing off objects etc.

    The SK Scene extends infinitely in all directions and your device's screen is simply a moveable window onto the scene. If you decide in your game that a sprite which moves offscreen is no longer needed, then you need code to detect this and then issue 'RemoveFromParent' against the sprite.