Ryan Burke
Ryan Burke

Reputation: 21

How do I get the location of a UI touch in Sprite Kit?

I would like to get the location of the touch in the UI, and use that location to determine what direction the sprite runs. For example, if the touch is on the left side of the screen, the user runs left, and if the touch is on the right side of the screen, the user runs right.

Upvotes: 2

Views: 962

Answers (3)

crashoverride777
crashoverride777

Reputation: 10664

As KnightOfDragon mentioned for SpriteKit the correct way would be

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch in touches {
        let location = touch.locationInNode(self) // self is the current SKScene
        let node = nodeAtPoint(location)

        // To get the touched half of the screen I do this
        if location.x < CGRectGetMidX(self.frame) {
             // left half touched, do something
        }

        if location.x > CGRectGetMidX(self.frame) {
            // right half touched, do something
        }
    }
}

Upvotes: 1

Mr_Pouet
Mr_Pouet

Reputation: 4280

@KnightOfDragon's answer is the right one here.

You should use directly

func locationInNode(_ node: SKNode) -> CGPoint

More about Touch events in SpriteKit over here: documentation

Upvotes: 1

LuKenneth
LuKenneth

Reputation: 2237

Try something like this

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {
        let position = touch.locationInView(view)
        print(position)
        }
    }

Upvotes: 3

Related Questions