ryan clothier
ryan clothier

Reputation: 129

touch moking sprite by tap not swipe swift

I have a block in my code where the sprite will only move if you tap the screen. I would like to have this behaviour when I swipe up or down instead. Here is my code

import SpriteKit
import UIKit

class GameScene: SKScene {
    var porker:Porker!
    var touchLocation = CGFloat()
    var gameOver = false


    override func didMoveToView(view: SKView) {
        addBG()
        addPig()
    }

    func addBG() {
        let bg = SKSpriteNode(imageNamed: "bg");
        addChild(bg)
    }

    func addPig() {
        let Pig = SKSpriteNode(imageNamed: "pig")
        porker = Porker(guy:Pig)
        addChild(Pig)
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {


        for touch: AnyObject in touches{
            if !gameOver {
                touchLocation = (touch.locationInView(self.view!).y * -1) + (self.size.height/2)
            }

        }
        let moveAction = SKAction.moveToY(touchLocation, duration: 0.5)
        moveAction.timingMode = SKActionTimingMode.EaseOut
        porker.guy.runAction(moveAction)
    }
}


    func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
    }

Upvotes: 3

Views: 62

Answers (1)

Stefan
Stefan

Reputation: 5461

Replace touchesBegan with this code:

// Store the start touch position
let yTouchCurrentPosition = 0.0
let yTouchDistance = 0.0
let yTouchStartPosition = 0.0
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch in touches {
        yTouchStartPosition = touch.locationInNode(self).y
    }
}

// Calculate the distance of the touch movement
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch in touches {
        yTouchCurrentPosition = touch.locationInNode(self).y
        yTouchDistance = yTouchStartPosition - yTouchCurrentPosition
    }
}

// Reset all movement states and move sprite
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    yTouchCurrentPosition = 0.0
    yTouchDistance = 0.0
    yTouchStartPosition = 0.0

    let moveAction = SKAction.moveToY(CGPoint(porker.guy.location.x, porker.guy.location.y + yTouchDistance), duration: 0.5)
    moveAction.timingMode = SKActionTimingMode.EaseOut
    porker.guy.runAction(moveAction)
}

Upvotes: 1

Related Questions