在触摸时移动SKSpriteNode以创建按钮效果

时间:2019-04-12 18:50:43

标签: swift sprite-kit

我目前正在创建手机游戏的主菜单,但是它工作正常,但是为了使其外观更好,我想在触摸一个按钮图像的SKSpriteNodes时添加一种效果。在过渡到游戏之前,我希望它先稍微下移然后再向上移动,但遇到一些困难。当前,当按下按钮时,会将场景更改为游戏场景。

class MainMenuScene: SKScene{
    let startGame = SKSpriteNode(imageNamed: "StartButton")
    override func didMove(to view: SKView) {


        let background = SKSpriteNode(imageNamed: "Menu") 
        background.size = self.size
        background.position = CGPoint(x: self.size.width/2, y:self.size.height/2)
        background.zPosition = 0
        self.addChild(background)


        startGame.position = CGPoint(x: self.size.width/2, y: self.size.height*0.6)
        startGame.zPosition = 1
        startGame.name = "startButton"
        self.addChild(startGame)


}

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

    for touch: AnyObject in touches{

        let pointOfTouch = touch.location(in: self)
        let nodeITapped = atPoint(pointOfTouch)


        if nodeITapped.name == "startButton" {

            let sceneToMoveTo = GameScene(size: self.size)
            sceneToMoveTo.scaleMode = self.scaleMode
            let myTransition = SKTransition.fade(withDuration: 0.5)
            self.view!.presentScene(sceneToMoveTo, transition: myTransition)
        }

    }
}








}

1 个答案:

答案 0 :(得分:0)

您可以在函数touchesEnded中创建逻辑,然后在按钮中调用SKAction,将moveToScene逻辑作为完成传递。 像这样:

var shouldMoveToNewScene: Bool = False

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

for touch: AnyObject in touches{

    let pointOfTouch = touch.location(in: self)
    let nodeITapped = atPoint(pointOfTouch)

    shouldMoveToNewScene = nodeITapped.name == "startButton" ? True : False

}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard shouldMoveToNewScene, touces.count == 1 else { return }

    startButton.run(myAnimation, completion: {
        moveToScene()
    })
}

private func moveToScene() {
    //do your transition scene logic here
{

我还没有尝试过,但是希望您能理解。

如果您不熟悉SKAction,则应考虑遵循此guide