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?