Alex Ingram
Alex Ingram

Reputation: 434

Swift detecting touch in left and right side of screen SKScene

I'm trying to detect whether the user is touching either the left or right hand side of the screen in an SKScene.

I've put the following code together however it is only outputting "Right" regardless of where is touched.

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



    for touch in touches {
        let location = touch.location(in: self)

        if(location.x > self.frame.size.width/2){
            print("Left")
        }

        else if(location.x < self.frame.size.width/2){
            print("Right")
        }
    }
}

Upvotes: 2

Views: 2279

Answers (2)

Leon Jakonda
Leon Jakonda

Reputation: 87

For Swift 5.0

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

    let touch = touches.first
    if let location = touch?.location(in: UIScreen.main.focusedView) {
        let halfScreenWidth = UIScreen.main.bounds.width / 2
        if location.x < halfScreenWidth {
            print("Left touch")
            //Your actions when you click on the left side of the screen
        } else {
            print("Right touch")
            // Your actions when you click on the right side of the screen
        }
    }
}

Another method with Gesture Recognizer (this method resolves the conflict between swipe and tap)

override func viewDidLoad() {
    tapObserver() 
}

private func tapObserver() {
    let tapGestureRecongnizer = UITapGestureRecognizer(target: self, action: #selector(executeTap))
    tapGestureRecongnizer.delegate = self
    view.addGestureRecognizer(tapGestureRecongnizer)
}

@objc func executeTap(tap: UITapGestureRecognizer) {
    let point = tap.location(in: self.view)
    let leftArea = CGRect(x: 0, y: 0, width: view.bounds.width/2, height: view.bounds.height)
    if leftArea.contains(point) {
        print("Left tapped")
        //Your actions when you click on the left side of the screen
    } else {
        print("Right tapped")
        //Your actions when you click on the right side of the screen
    }
}

Upvotes: 0

Lucas Buhl-Nielsen
Lucas Buhl-Nielsen

Reputation: 119

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

    for touch in touches {
        let location = touch.location(in: self)

        if(location.x < 0){
            print("Left")
        }  
        else {
            print("Right")
        }
    }
}

That seems to work. Before you were checking whether the touch was to the left/right-hand side of the left-hand side of the screen, hence it always gave you right. For example, on an iPhone 7 plus, you would be checking if your touch (let's say the x was 20) was to the right-hand side of left-hand side of 365. Since 20 is smaller than 365, it said that you had clicked on the right-hand side.

Upvotes: 2

Related Questions