简体   繁体   中英

Spritekit: How do you call touches began & in touches separately?

I have a game in Sprite Kit and this game will start as soon as I touch the screen. I also want a button in the game that if I touch, I only want that to be called and not the actual game. Here's an example. I have "touches began touched" being called when I touch anywhere on the screen. I also have a button that if I could, it calls "button touched". My problem is, if I touch the button and call "button touched", it also calls "touches began touched". Why? Thanks!

class GameScene: SKScene {

var button: SKNode! = nil

override func didMoveToView(view: SKView) {

    button = SKSpriteNode(color: SKColor.redColor(), size: CGSize(width: 100, height: 44))

    button.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame));

    self.addChild(button)


}

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

    print("touches began touched")

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

        if button.containsPoint(location) {
            print("button touched")

    }
}

If I understood right, you want to start the game when the touchesBegan gets called. But this function is called every time you touch the screen, no matter where. So you can just do it like this:

class GameScene: SKScene {

var button: SKNode! = nil

override func didMoveToView(view: SKView) {

    button = SKSpriteNode(color: SKColor.redColor(), size: CGSize(width: 100, height: 44))

    button.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame));

    self.addChild(button)


}

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

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

        if button.containsPoint(location) {
            print("button touched")

    }
        else {
            //start the game here
    }
}

This way the game will start every time you touch the screen except when you touch the button.

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