【问题标题】:Swift touch recognition not recognising one half of screen being touched快速触摸识别无法识别被触摸的一半屏幕
【发布时间】:2017-02-28 02:22:45
【问题描述】:

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

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

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

【问题讨论】:

    标签: swift touch skscene


    【解决方案1】:

    如果您使用 SpriteKit 项目的默认场景,则锚点为 (0.5, 0.5),它将场景的原点放置在中心。如果要测试触摸位置是左还是右,则应将条件检查更改为(无论锚点如何都可以):

    for touch in touches {
        let location = touch.location(in: self)
    
        if(location.x < frame.midX){
            print("Left")
        }
    
        else if(location.x > frame.midX){
            print("Right")
        }
    }
    

    更多详情请访问:SKScene

    【讨论】:

    • 谢谢!!一直在用这个拉我的头发。
    • 无论锚点如何,您都可以使用 frame.midX 使其更清晰。 “location.x
    猜你喜欢
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多