user4509200
user4509200

Reputation:

Check if touch is active in Sprite Kit (Swift)

So, I am developing a game in Sprite Kit for the first time ever. This is a great learning experience for me!

However, I have encountered an issue :( I do not know how to make it so that a function is called repeatedly while a touch is active (for example, a function is called every 0.5 sec that touch is 'touching'). So, I was considering having an SKAction run and then cancel/delete it when touch is released... but I decided against that.

Instead, I was hoping for a function that checks if there is a touch, but not necessarily that a touch was pressed, released, or changed location, i.e. check if a touch is touching, period.

If this is not possible, is the easiest way for me to overcome this quandary what I was thinking of initially, or is there something easier?

Thanks so much in advance!

Upvotes: 0

Views: 189

Answers (1)

ABakerSmith
ABakerSmith

Reputation: 22939

If I was you, I would use an SKAction (or several) because, in my opinion, it helps keep my code cleaner; you run an SKAction in one place and then you don't have to worry about it again. This helps keep the update method free of lots of game logic.

In your comment you mentioned not being sure how to call a function using an SKAction. You can use SKAction.runBlock for that; it takes a closure (or function) that has no arguments and returns Void.

Alternatively, you could use SKAction.customAction... to create your own action running a function, although it's not appropriate in this situation. The documentation has more information on custom actions, here's a quick example though: How to create custom SKActions?

Anyhow, Here's how I'd achieve what you were after:

class GameScene: SKScene {
    let actionID = "TouchActionID"

    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        let wait = SKAction.waitForDuration(0.5)
        let block = SKAction.runBlock { println("Hello World") }
        let sequence = SKAction.sequence([wait, block])

        // Use `actionID`, defined earlier, as the key. 
        // This allows you to cancel the `SKAction`.
        self.runAction(SKAction.repeatActionForever(sequence), withKey: actionID)
    }

    // Cancel the SKAction if the touch ended or was cancelled. Cancelling 
    // could occur if the application resigns being active, for example.
    // See UIResponder documentation for more information.
    override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
        self.removeActionForKey(actionID)
    }

    override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
        self.removeActionForKey(actionID)
    }
}

Hope that helps!

Upvotes: 1

Related Questions