newtocoding
newtocoding

Reputation: 109

How do I add a touch and hold gesture to my node in Swift Spritekit?

I have this game where my node is in the middle of the screen and if I hold the left part of the screen the node will move to the left and if I hold on the right part of the screen the node will move to the right. I tried everything but cant seem to get it to work. Thank you! (I have some code but its not doing what I want it to do. If you want to see it and what it does ill put it up.)

EDIT CODE:

    var location = touch.locationInNode(self)

    if location.x < self.size.width/2 {
        // left code
        let moveTOLeft = SKAction.moveByX(-300, y: 0, duration: 0.6)
        hero.runAction(moveTOLeft)
    }
    else {
        // right code
        let moveTORight = SKAction.moveByX(300, y: 0, duration: 0.6)
        hero.runAction(moveTORight)


    }

Upvotes: 1

Views: 2093

Answers (1)

Beau Nouvelle
Beau Nouvelle

Reputation: 7252

You have to do a check on the position of your touch in each update to determine the direction you want your character to move.

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    var touch = touches.first as! UITouch
    var point = touch.locationInView(self)
    touchXPosition = point.x
    touchingScreen = true
}

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

override func update(currentTime: CFTimeInterval) {
    if touchingScreen {
        if touchXPosition > CGRectGetMidX(self.frame) {
            // move character to the right.
        }
        else {
            // move character to the left. 
        }
    }
    else { // if no touches.
        // move character back to middle of screen. Or just do nothing.
    }
}

Upvotes: 4

Related Questions