how to move the sprite when touch the screen and disable when I tap the screen

435 Views Asked by At

I'm making a game where I move a sprite across the screen, but if I tap on the screen it will move to that location and I only want it to move if I hold my finger on the screen so the sprite will follow my finger and it wouldn't teleport through my objects

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let touchLocation = touch.location(in: self)
            player.position.x = touchLocation.x

        }
    }

I tried this (the player is my sprite) and it works, when I move my finger the sprite will follow, but if I tap fx on the side of the screen it would teleport to that position and I​ don't want that to happen.

1

There are 1 best solutions below

1
George On

Try the following code:

var isDragging = false
var player = /* SKSpriteNode or whatever */


override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let touchLocation = touch.location(in: view)
        if player.contains(touchLocation) {
            isDragging = true
        }
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard isDragging else { return }

    if let touch = touches.first {
        let touchLocation = touch.location(in: view)
        player.position.x = touchLocation.x
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    isDragging = false
}

touchesBegan - Makes sure that the touch location is somewhere within the player, by using contains().

touchesMoved - If the player is being dragged, move the player to the touch's location.

touchesEnded - When the touch has ended, dragging will stop.