如何在 Swift Spritekit 中向我的节点添加触摸和按住手势



我有一个游戏,我的节点在屏幕中间,如果我按住屏幕的左侧,节点将向左移动,如果我按住屏幕的右侧,节点将向右移动。我尝试了一切,但似乎无法让它工作。谢谢!(我有一些代码,但它没有做我想让它做的事情。如果你想看到它以及它有什么不好的地方把它放上去。

编辑代码:

    var location = touch.locationInNode(self)
    if location.x < self.size.width/2 {
        // left code
        let moveTOLeft = SKAction.moveByX(-300, y: 0, duration: 0.6)
        hero.runAction(moveTOLeft)
    }
    else {
        // right code
        let moveTORight = SKAction.moveByX(300, y: 0, duration: 0.6)
        hero.runAction(moveTORight)

    }

在每次更新中,你需要检查一下你的触摸位置,以确定你希望角色移动的方向。

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    var touch = touches.first as! UITouch
    var point = touch.locationInView(self)
    touchXPosition = point.x
    touchingScreen = true
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
    super.touchesEnded(touches, withEvent: event)
    touchingScreen = false
}
override func update(currentTime: CFTimeInterval) {
    if touchingScreen {
        if touchXPosition > CGRectGetMidX(self.frame) {
            // move character to the right.
        }
        else {
            // move character to the left. 
        }
    }
    else { // if no touches.
        // move character back to middle of screen. Or just do nothing.
    }
}

最新更新