Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Handling Click Events On SKSpriteNode

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 36
    Comment on it

    Hi,

     

    Like UIButtons we don’t have IBActions for SKSpriteNode and what if we have to trigger the click event on SpriteNodes. Solution comes here by handling touch methods provided by UIResponder class.

    Start by creating a subclass of SpriteNode(using SKSpriteNode here) and add touchesBegan and touchesEnded method.

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    
           // Do your stuff here.
    }
        
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
           
           completionHandler(self)
           // Do your stuff here.
    }


    Once you are done with above step create a call back or protocol to handle the touch/click event(s).

    var completionHandler = {(object : TDAnimatedSpriteButton)->Void in
            
    }

    // we are using closure here.

    From now, start using this subclass where you want to have handle the click events for Sprites, with the help of closure/callback you can easily catch whenever a SKSpriteNode is touched.


    Code Snippet:

    class TDAnimatedSpriteButton: SKSpriteNode {
    
        var completionHandler = {(object : TDAnimatedSpriteButton)->Void in
            
        }
        
        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
             // Do your stuff here.
        }
        
        override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        
            completionHandler(self)
            // Do your stuff here.
        }
    }

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: