Giving properties of a UIButton to a SKSpriteNode in SpriteKit

守給你的承諾、 提交于 2019-12-22 01:05:49

问题


I was wondering if there was a way to give the properties of a UIButton like darkening the button once it has been pressed,... to a SKSpiteNode since an SKSpiteNode has more customization and because I am using SpriteKit. I have seen 1 other question like this but none of the answers worked. Here is the code I have to create the SKSpriteNode and to detect a touch on it:

import SpriteKit
class StartScene: SKScene {    
var startButton = SKSpriteNode()
override func didMoveToView(view: SKView) {
    startButton = SKSpriteNode(imageNamed: "playButton")
    startButton.size = CGSize(width: 100, height: 100)
    startButton.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2 - 50)
    self.addChild(startButton)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    /* Called when a touch begins */

    for touch in touches {
        let location = touch.locationInNode(self)

        if startButton.containsPoint(location){
           // When it has been selected
        }   
    }
}
//...

Pleas help. Thanks in advance... Anton


回答1:


I have always achieved this by adding code to the touches began, and touches ended method. Inside of these methods I simply set the sprites color to black, and then change its color blend factor. Let me know if this works for you!

  //This will hold the object that gets darkened
    var target = SKSpriteNode() 
    //This will keep track if an object is darkened
    var have = false

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
var first = touches.first as! UITouch
        var location:CGPoint = first.locationInNode(self)
        touchP = location
        mouse.position = touchP
        var node:SKNode = self.nodeAtPoint(location)
       if let button = node as? SKSpriteNode
       {
          target = button
           have = true
       }
       else
       {
         have = false
       }

       if (have == true)
       {
           target.color = UIColor.blackColor()
           target.colorBlendFactor = 0.2

       }
}

override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
            if (havet == true)
            {
                target.color = UIColor.blackColor()
                target.colorBlendFactor = 0
                target = SKSpriteNode()
                have = false

            }

}


来源:https://stackoverflow.com/questions/35258342/giving-properties-of-a-uibutton-to-a-skspritenode-in-spritekit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!