简体   繁体   中英

How do create a button using Sprite Kit and Swift?

Hi I am currently working on a platforming game for iOS. I would like to be able to move my character left or right by the press of a button. How is it that I can create a button? Do I use UIKit or an SKNode ?

If possible I would like to know both methods or the most efficient.

Thanks in advance!!!!

-Matt A.

The common strategy to handle user press event is using system provided func touchesBegan:touches withEvent:event :

//add trigger node into your scene
let triggerNode = SKSpriteNode(texture: SKTextureAtlas(named: "scenery.atlas").textureNamed(soundImg))
triggerNode.name = "TriggerNodeName"
triggerNode.zPosition = 10
addChild(triggerNode)

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches{
        let location = touch.location(in: self)
        let touchNode = atPoint(location)
        print("\(touchNode.name)")

        if touchNode.name == "TriggerNodeName"{
            //write your logic here
            ...
            return
        }
     }
}

Here is what I did: When touchesBegan my player would go left. Then I used touchesEnded to tell my player to stop.

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        for touch in touches{
            let location = touch.location(in: self)
            let touchNode = atPoint(location)
            print("\(touchNode.name)")

            if touchNode.name == "Button"{
                //write your logic here
                thePlayer.goLeft()
                print("Pressed!")
            }
        }


    }
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {


        for touch in touches{
            let location = touch.location(in: self)
            let touchNode = atPoint(location)
            print("\(touchNode.name)")

            if touchNode.name == "Button"{
                //write your logic here
                thePlayer.stop()
                print("Pressed!")
            }
        }


    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM