Search code examples
swiftsprite-kitskspritenodetouchesbegan

Expose the Object that owns a Property


Though I'm using SpriteKit, this is a general Swift question:

I am creating game classes that will all use SKSpriteNodes (NPC, Player, Powerup, and so on). I want to store SKSpriteNodes as properties on these objects, rather than inheriting from SKSpriteNode (favoring composition over inheritance).

This works great, except I can't capture which game object class was tapped by a user with the touchesBegan function. SKScene's nodeAtPoint only returns the instance of the SKSpriteNode, with no way to know which game object owns it. I can loop through all of my game object instances and compare their sprite nodes to the touched node to create the link I need . . . but that seems very inefficient.

Is there a way to expose the object that 'owns' the property of the touched node? Or another method to do what I'm describing? Or should I just inherit from SKSpriteNode like I see in most example games?


Solution

  • Note that in this case you need bidirectional relationships - your game objects need to access the nodes but also the nodes need to access their game objects.

    I don't think you can completely avoid inheritance in this case. The simplest method would be to inherit from SKSpriteNode and add a link to the object that owns it (a weak property called owner, for example).