只有在按下时才能移动精灵?

时间:2016-06-10 04:51:15

标签: swift xcode sprite game-physics

每当我按下屏幕右侧时屏幕上都有一个圆圈向右移动,当我按下屏幕左侧时离开。现在我需要这样做,当我开始触摸时,我的圆圈向右移动,但如果我松开触摸,那么圆圈将停止,直到我再次按下屏幕。

这是我的touchesBegan功能。

    for touch: AnyObject in touches {


    let location = touch.locationInNode(self)
    if location.x < self.size.width / 2 {

        let moveLeft = SKAction.moveToX(self.frame.width / 3, duration: 1.0)
        Ball.runAction(moveLeft)

    }
    else {

        let moveRight = SKAction.moveToX(self.frame.width / 1.445, duration: 1.0)
        Ball.runAction(moveRight)


        }





    }

这是我到目前为止所拥有的。

1 个答案:

答案 0 :(得分:0)

基本上是这样的:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)
        if location.x < self.size.width / 2 {

            let moveLeft = SKAction.moveToX(self.frame.width / 3, duration: 1.0)
            Ball.runAction(moveLeft, withKey:"moveLeft")
        }
        else {
            let moveRight = SKAction.moveToX(self.frame.width / 1.445, duration: 1.0)
            Ball.runAction(moveRight withKey:"moveRight")
        }
    }
}

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    Ball.removeActionForKey("moveLeft")
    Ball.removeActionForKey("moveRight")
}

我建议你在每次需要的时候把钥匙比把它们硬编码为弦更聪明一些,但这就是要点。