Reputation: 1852
Currently I'm making a game with swift spritekit and want the character look left when the finger moves the character to the left in touchesMoved. Since, I started development with swift and spritekit just a few days ago I find it hard to implement this action. How can I detect left or right in the code below ?
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch in (touches as! Set<UITouch>) {
let location = touch.locationInNode(self)
playerSprite.position.x = touch.locationInNode(self).x
}
Upvotes: 0
Views: 413
Reputation: 22343
You can check if the current x-position of your touch is bigger or smaller than the position before.
To achieve that, you should create a variable to store the location of your last touch. For example:
var lastXTouch:CGFloat = -1
Then in the touchesMoved-method you check the location and check if the previous location was more on the left or more on the right side:
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch in (touches as! Set<UITouch>) {
let location = touch.locationInNode(self)
if lastXTouch > location.x{
//Finger was moved to the left. Turn sprite to the left.
}else{
//Finger was moved to the right. Turn sprite to the right.
}
lastXTouch = location.x
playerSprite.position.x = touch.locationInNode(self).x
}
Upvotes: 2
Reputation: 1545
Put in a gesture recognizer when you want to be able to detect the swipe:
var leftSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipe:"))
leftSwipe.direction = .Left
var rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipe:"))
rightSwipe.direction = .Right
self.view.addGestureRecognizer(leftSwipe)
self.view.addGestureRecognizer(rightSwipe)
Then, you need to implement the handler method that is called - handleSwipe:
func handleSwipe(sender:UISwipeGestureRecognizer){
if (sender.direction == .Left){
//swiped left
//change your texture here on the sprite node to make it look left
}
if (sender.direction == .Right){
//swipe right
//change texture here on sprite to make it look right
}
}
Upvotes: 1