Search code examples
sprite-kitswift3game-physicsxcode8touches

Touch implementation in game


I am using Swift 3 with Xcode 8 and I am trying to make simple game with SpritKit. Basically what I'm trying to do is allow player to move my sprite only left and right ( drag it on screen ) and after realising finger ( touch ended ) apply impulse on sprite. I have managed to do that BUT i want that to happen only on first touch, so after applying impulse on sprite player cannot interact with sprite anymore until some collison happens or simillar. Below is my code which works all the time not only on first touch.

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



}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches {

        let location = t.location(in: self)

        if player.contains(location)
        {
            player.position.x = location.x
        }
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches {

        if let t = touches.first {

            player.physicsBody?.isDynamic = true
            player.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 50))
        }
    }
}

Solution

  • As Whirlwind commented, you just need a boolean value to determine when you should control the object:

    /// Indicates when the object can be moved by touch
    var canInteract = true
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        for t in touches {
            let location = t.location(in: self)
            if player.contains(location) && canInteract
            {
                player.position.x = location.x
            }
        }
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        for t in touches {
    
            if let t = touches.first && canInteract {
                canInteract = false //Now we cant't interact anymore.
                player.physicsBody?.isDynamic = true
                player.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 50))
            }
        }
    }
    /* Call this when you want to be able to control it again, on didBeginContact
       after some collision, etc... */
    func activateInteractivity(){
        canInteract = true
        // Set anything else you want, like position and physicsBody properties
    }