1

I am trying to use GameplayKit to implement all the entities/components of a 2D game made with SpriteKit. The first component that I have created is the SpriteComponent:

class SpriteComponent:GKComponent
{
    let node:SKSpriteNode

    init(texture:SKTexture) {
        node = SKSpriteNode(texture: texture, color: SKColor.clear, size: texture.size())
        super.init()
    }

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

Which is meant to be used by all the components that needs to be added to the scene. Next I wanted to add a component to fire bullets, which I called FiringComponent. Since a bullet is a graphical item, it could be an entity implementing a SpriteComponent, so I wrote this code:

class Bullet:GKEntity
{
    var velocity:CGPoint

    var node:SKSpriteNode
    {
        return self.component(ofType: SpriteComponent.self)!.node
    }

    init(withVelocity velocity:CGPoint)
    {
        self.velocity = velocity
        super.init()
        let spriteComponent = SpriteComponent(texture: SKTexture(imageNamed: "Bullet"))
        addComponent(spriteComponent)
    }

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

    override func update(deltaTime seconds: TimeInterval)
    {
        self.node.position += self.velocity * CGFloat(seconds)
        // I have overridden the CGPoint += and * operators
    }
}

Next comes the doubt: should the FiringComponent add directly the bullet entity to the scene? a possible implementation of the FiringComponent could be of adding a Bullet entity that should be added to the game hierarchy and updated at each frame. But I think that this logic is flawed, because this way the component needs to have a variable that points not only to the game scene, but also to the object that holds all the entities and updates them periodically. This way I have to write contorted code just to fire a bullet. I am searching for a neat and clean way to implement that: any suggestion?

Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187
  • 1
    For clarity, the `FiringComponent` would be something like a gun entity (rather a component of the gun). As an FYI, if you're going to ECS, then you would probably make velocity another component. – Mobile Ben Oct 23 '16 at 01:37
  • 1
    I read an interesting [article](http://www.gamedev.net/page/resources/_/technical/game-programming/understanding-component-entity-systems-r3013), with the idea about `ECS` is that components are just containers of data, entities are just a collection of components and all the action is driven by the`system`. This contrasts with object oriented programming techniques where logic and data are encapsulated. – Mark Brownsword Oct 26 '16 at 20:17

0 Answers0