GKEntity and state machines

540 views Asked by At

I'm working on a small project using SpriteKit and GameplayKit. It's my first time using an entity/component system and I'm loving it. But now, I'm at a point where I need to keep track of my entities states (Spawning, Normal, Removing) so they don't interact during their spawning phase (which may or may not include actions to animate the thing) and their removing phase.

So far, I've created a EntityStateComponent which instanciate a GKStateMachine with the different states and since there is no need for per-frame updates it's not that complicated. The thing is that this state is more entity related than component related and I'm wondering if it would make sense to subclass from GKEntity and add the state machine in there instead of in a component.

Your thoughts?

PS: I'm already sub-classing from GKEntity just to have a convenience init() that creates all the components

1

There are 1 answers

4
Mark Brownsword On

You are right, state is entity related, not component related. Put the state machine into the entity directly, or create an entity base class that all your entities inherit from.

class VisualEntityBase : GKEntity, VisualEntity {
    var node: SKSpriteNode!
    var stateMachine: GKStateMachine!


    // MARK: Initialization

    init(imageNamed: String, atStartPosition: CGPoint) {
        super.init()

        // Initialise Texture
        let texture = SKTexture(imageNamed: imageNamed)

        // Initialise Node
        self.node = SKSpriteNode(texture: texture, size: texture.size())
        self.node.position = atStartPosition

        // Initialise StateMachine
        self.stateMachine = GKStateMachine(states: [
            VisualEntityIdle(),
            VisualEntityPendingMove(),
            VisualEntityMoving()
        ])

        self.stateMachine.enter(VisualEntityIdle.self)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}