当用户触摸屏幕并按住屏幕时,我希望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))
}
}
答案 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)
希望有所帮助!