简体   繁体   中英

Replay button doesn't work. (Swift, SpriteKit)

Once my game ends, it displays a button for replay, but I can't understand how to let Xcode know if there is a touch after the game has ended. My replay button's code is in didBeginContact Method and is as follows:

func didBeginContact(contact: SKPhysicsContact) {
       if (.....) {
            ..........
      }  else {
         replayButton = SKSpriteNode(imageNamed: "ReplayButton")
            replayButton.position = CGPoint(x: size.width / 1.75, y: size.height / 2.5)
            replayButton.name = "replayButton"
            self.addChild(replayButton)
       }

New Swift file:

class button: SKSprideNode {

let replayButton = button(imageNamed: "replayButton")


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

var touch = touches as!  Set<UITouch>
var location = touch.first!.locationInNode(self)
var node = self.nodeAtPoint(location)


if (node.name == "replayButton") {

    let myScene = EMode(size: self.size)
    let reveal = SKTransition.fadeWithDuration(2.0)
    self.scene!.view(myScene, transition: reveal)  //error on this line
    }
  }
}

You need to set the replay button's user interaction enabled to true like this:

replayButton.userInteractionEnabled = true

Then you just need to listen for when the button or scene is touched. One way to do that is make a subclass of SKSpriteNode called Button or something, and override the touchesBegan method.

EXAMPLE:

ButtonClass

class ExampleButton: SKSpriteNode {
    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        //do stuff here
    }
}

Button Initialization

let button = ExampleButton(imageNamed: "ButtonImage")
button.userInteractionEnabled = true

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