dancingbush
dancingbush

Reputation: 2281

How to Remove an Entity form a SKScene

Components of entities can be removed with:

entity.removeComponentForClass(SpriteComponent.self);
entity.removeComponentForClass(PhysicsComponent.self);

How are Entities removed from a SKScene?

There are plenty of tutorials about removing components, but I can't find anything explicit about removing entities. Is there something like removing a node?

node.removeFromParent();

Upvotes: 1

Views: 439

Answers (1)

Tim Newton
Tim Newton

Reputation: 1521

I adapted this from Apple's DemoBots which contains samples for the RenderComponent and LayerConfiguration.

Array was extended using Swift solution here >> Array extension to remove object by value

var entities = [GKEntity]()

/// Stores a reference to the root nodes for each world layer in the scene.
var layerNodes = [LayerConfiguration:SKNode]()

func addEntity(entity: GKEntity)
{
    self.entities.append(entity)

    for componentSystem in self.componentSystems
    {
        componentSystem.addComponent(foundIn: entity)
    }

    // If the entity has a `RenderComponent`, add its node to the scene.
    if let renderNode = entity.component(ofType: RenderComponent.self)?.node
    {
        self.addNode(node: renderNode, toLayer: .actors)
    }
}

func removeEntity(entity:GKEntity)
{
    for componentSystem in self.componentSystems
    {
        componentSystem.removeComponent(foundIn: entity)
    }

    if let renderNode = entity.component(ofType: RenderComponent.self)?.node
    {
       renderNode.removeFromParent()
    }

    self.entities.remove(entity)
}

func addNode(node: SKNode, toLayer layer: LayerConfiguration)
{
    // 
    let layerNode = self.layerNodes[layer]!

    layerNode.addChild(node)
}

Upvotes: 0

Related Questions