When the user touches the screen and holds it, I'd like the SKSpriteNode
to fly up, and after user stops holding touch, it again falls down to the ground. Right now I'm using tapping to move the node up and setting the gravity to false in the touchesEnded to make it fall to the ground. How would I get this to work. Thanks!
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))
}
}
Firstly, you need to keep track of when the user is touching and holding the screen. You can do this like so, in your 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
}
Secondly, you now need to make the object move upwards whilst the user is pressing the screen, again in your SKScene
:
override func update(currentTime: CFTimeInterval) {
if touchingScreen {
// Adjust the CGVector to suit your needs.
sprite.physicsBody!.applyImpulse(CGVector(dx: 0, dy: 50))
}
}
Alternatively, if you want your object to move upwards at a constant velocity, replace:
sprite.physicsBody!.applyImpulse(CGVector(dx: 0, dy: 50))
with
sprite.physicsBody!.velocity = CGVector(dx: yourDx, dy: yourDy)
Hope that helps!