5AMWE5T
5AMWE5T

Reputation: 841

Get touch location inside the bounds of the screen with swift?

I have a scene that is larger than the size of the device screen, and there is a camera that follows the player around the scene. I want to move the player to the right if the user touches on the right side of the screen and to the left if they touch on the left side. But since my scene is larger than my phone screen, in the touchesBegan method there are problems when the user gets to the far edges of the scene. If the player goes to the left of the scene, even if the user touches on the right side of the screen it still registers as being a "left touch" because the entirety of the phone screen is filled only by the left side of the scene.

Here is what I have in my touchesBegan method:

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

    let touch = touches.first
    if let location = touch?.location(in: self) {
        print(location)

        if location.x < 0 {
            player.physicsBody?.applyImpulse(CGVector(dx: -8, dy: 0))
        } else {
            player.physicsBody?.applyImpulse(CGVector(dx: 8, dy: 0))
        }
    }
}

I tried changing the touch?.location(in: self) part but that seems to have no effect. Is there a way to do record where the user touches relative to the bounds of the SCREEN, not the scene?

Upvotes: 1

Views: 553

Answers (1)

Arash Etemad
Arash Etemad

Reputation: 1909

You can use UIScreen.main.focusedView instead of self.

Upvotes: 3

Related Questions