首页 > 解决方案 > 在 spritekit 游戏中获取屏幕的触摸位置

问题描述

我有一个精灵套件游戏,我想知道用户是否触摸了屏幕的左侧、右侧或中间(25/50/25)

在我触摸屏幕最左侧的那一刻,它说我在 x 轴上触摸 -450,而它应该是 0。我假设它获得了相对于场景的触摸位置,并且锚点开始 450 像素到右边,当我触摸 0 时给我 -450。

由于这是一个横向滚动条,因此移动 achor 不起作用,我需要屏幕的触摸位置:

override func touchesBegan(_ touches: Set<UITouch>,with event: UIEvent?){
    var touchLeft : Bool = false
    var touchRight : Bool = false
    var touchMiddle : Bool = false

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

        if(location.x < self.size.width/4){
            touchLeft = true
            print("Left")
        } else if(location.x > ((self.size.width/4) * 3)){
            touchRight = true
            print("Right")
        } else {
            touchMiddle = true
            print("Middle")
        }
    }
}

标签: iosswiftsprite-kituitouch

解决方案


你几乎拥有它,只需考虑负数。

如果您不知道,SKScene 默认的中心是 0。这是因为默认锚点是 0.5,0.5。

由于您使用相机来处理滚动,因此您希望使用 touch.location(in: self.camera)这样的方法,以便您始终相对于相机所在的位置而不是场景所在的位置进行触摸。

因此,只需将您的代码更改如下:

override func touchesBegan(_ touches: Set<UITouch>,with event: UIEvent?){
    var touchLeft : Bool = false
    var touchRight : Bool = false
    var touchMiddle : Bool = false

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

        if(location.x < -self.size.width/4){
            touchLeft = true
            print("Left")
        } else if(location.x > ((self.size.width/4))){
            touchRight = true
            print("Right")
        } else {  //x is between -width / 4 and width / 4
            touchMiddle = true
            print("Middle")
        }
    }
}

推荐阅读