当在Swift Spritekit中触摸并按住屏幕时,如何移动节点?

时间:2015-04-23 16:19:34

标签: xcode swift touchesbegan

当用户触摸屏幕并按住屏幕时,我希望SKSpriteNode向上飞起,并且在用户停止触摸后,它再次落到地面上。现在我正在使用点击向上移动节点并在touchesEnded中将重力设置为false以使其落到地面。我怎么能让这个工作。谢谢!

   var touchingScreen = false

    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    super.touchesBegan(touches, withEvent: event)
    touchingScreen = true
}


    override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
    super.touchesCancelled(touches, withEvent: event)
    touchingScreen = false
}

override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
    super.touchesEnded(touches, withEvent: event)
    touchingScreen = false
}

 override func update(currentTime: CFTimeInterval) {
    if touchingScreen {
        // Adjust the CGVector to suit your needs.
        heroNode.physicsBody!.applyImpulse(CGVector(dx: 0, dy: 10))


    }
}

1 个答案:

答案 0 :(得分:3)

首先,您需要跟踪用户何时触摸并按住屏幕。您可以在SKScene

中执行此操作
var touchingScreen = false

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    super.touchesBegan(touches, withEvent: event)
    touchingScreen = true
}

override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
    super.touchesCancelled(touches, withEvent: event)
    touchingScreen = false
}

override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
    super.touchesEnded(touches, withEvent: event)
    touchingScreen = false
}

其次,您现在需要在用户按下屏幕时让对象向上移动,再次在SKScene

override func update(currentTime: CFTimeInterval) {
    if touchingScreen {
        // Adjust the CGVector to suit your needs.
        sprite.physicsBody!.applyImpulse(CGVector(dx: 0, dy: 50))
    }
}

或者,如果您希望对象以恒定速度向上移动,请替换:

sprite.physicsBody!.applyImpulse(CGVector(dx: 0, dy: 50))

sprite.physicsBody!.velocity = CGVector(dx: yourDx, dy: yourDy)

希望有所帮助!