【问题标题】:Swift detecting touch in left and right side of screen SKScene快速检测屏幕SKScene左右两侧的触摸
【发布时间】:2023-04-05 18:38:01
【问题描述】:

我正在尝试检测用户是否在 SKScene 中触摸屏幕的左侧或右侧。

我将以下代码放在一起,但无论触摸到哪里,它都只会输出“Right”。

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")
        }
    }
}

【问题讨论】:

  • 不会右大于 (>) 左小于 (
  • 没错..现在我触摸任何地方时它都会输出“Left”。

标签: ios swift skscene touches


【解决方案1】:
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")
        }
    }
}

这似乎行得通。在您检查触摸是否在屏幕左侧的左侧/右侧之前,因此它总是给您正确的。例如,在 iPhone 7 plus 上,您将检查您的触摸(假设 x 为 20)是否在 365 左侧的右侧。由于 20 小于 365,因此它表示您已点击右侧。

【讨论】:

    【解决方案2】:

    对于 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
            }
        }
    }
    

    手势识别器的另一种方法(该方法解决了滑动和点击之间的冲突)

    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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-15
      • 2023-04-01
      • 1970-01-01
      • 2016-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多