swiftcomponentsgameplay-kitskphysicscontact

Placing SKPhysicsContact within a GKComponent


At the moment, I use SKPhysicsContact to trigger a change in behaviour for my sprites, from within the GameScene. The problem is with each development, the game scene becomes longer and longer. Has anyone managed to make a GKComponent with SKPhysics embedded in it to make contact management simpler? How would this work?


Solution

  • Collision handling is difficult to handle well in an entity-component architecture because of the single point of dispatch (the physics world's contact delegate). But you can use that point to sort out involved entities and dispatch contact messages to the correct components.

    Apple's DemoBots sample code has one example of this. Here's a quick summary of how they do it:

    1. SK nodes for which contact handling is desired use a special subclass, EntityNode, which adds a back-reference to the node's owning entity (GKEntity or some subclass).

    2. In didBeginContact, sort out whether the contact wants handling and by whom. DemoBots does this by creating a ColliderType struct that helps to abstract the bit masks into "does type A want to collide / notify contacts with type B?" kinds of questions.

    3. After deciding who to notify, work out the owning entities/components for the colliding sprites and send contact messages on to them. That is, your custom entity or component classes should define their own contact handling messages.

    DemoBots uses a bunch of custom entity classes and handles contacts in each. You could just as well use fewer entity classes, and handle contacts in a component — in which case your step 3 above would involve looking up the ContactComponent (or whatever you call it) on the colliding entities and sending messages to them.