Stephen Haney

Sprite Touch Events using touchesBegan

Quick Sprite Recap

Last time we explored game element organization using a Sprite class to wrap our SKSpriteNodes. Now we can easily handle Sprite touch events.

touchesBegan and the nodeAtPoint method

The touchesBegan method is called every time there’s a touch event in your swift game. You can grab the touched SKSpriteNode with the the SpriteKit function nodeAtPoint. This gives us the SKSpriteNode itself, but not the instance of the Sprite wrapper class we’ve created with all of our events. We’ll have to store our Sprites somewhere that we can reference.

To keep all my Sprite and descendant classes organized, I’ve created a new class called GameLogic that I will instantiate in my GameViewController as a global variable named gameLogic. GameLogic will handle any rule checking for my game, keep track of game properties like points and lives remaining, and also maintain an array of every Sprite in the game. We’ll focus on the Sprite array for now.

class GameLogic {
    // all GameLogic needs to do for now is to keep an array of our Sprite wrapper class instances
    var sprites:Sprite[] = [];

Every time we create a new Sprite class, we’ll add the instance to GameLogic’s array. This gives us a handy list of all of our Sprites accessible at any point of our program.

Back to Touches!

Now we can find the correct Sprite wrapper class whenever an SKSpriteNode is touched:

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        for touch: AnyObject in touches {
            let location = touch.locationInNode(self)
            let touchedNode = nodeAtPoint(location);
            let touchedSpriteArray = gameLogic.sprites.filter { $0.sprite === touchedNode };
            if touchedSpriteArray.count > 0
                // if we touched a tile, fire its tap event

That’s it! Any Sprite we create will automatically have its onTap method called whenever it’s touched. You can override the onTap method on descendants for unique functionality.

I had to rush this post a bit due to a busy work week, but I hope it’s a somewhat helpful look at one way to keep game elements organized, and the benefits you gain from organization. Drop me a comment if I can clarify anything or help in any way. Cheers!