如何在视图中设置关于其位置的触摸

时间:2015-10-15 08:22:06

标签: sprite-kit location

我在SpriteKit中制作游戏。我有一个左块和一个右块。起初我以为使用nodeAtPoint与块进行交互,但在我的情况下它对玩家来说太不舒服了。我想这样做,如果玩家触摸屏幕左侧的任何地方 - 它会触发左侧区块,屏幕右侧会相应地触发右侧区块。怎么会这样呢?  现在,我在点上使用节点进行交互的代码如下所示:

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    /* Called when a touch begins */
    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)
        switch self.nodeAtPoint(location) {
        case self.leftblock:
            println("closeleft")
            leftblock.runAction(SKAction.animateWithTextures(leftArray, timePerFrame: 0.03, resize: true, restore: false))
        case self.rightblock:
            println("closeright")
            rightblock.runAction(SKAction.animateWithTextures(rightArray, timePerFrame: 0.03, resize: true, restore: false))
        default: break
        }
    }
}


override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
    /* Called when a touch begins */
    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)
        switch self.nodeAtPoint(location) {
        case self.leftblock:
            println("openleft")
            leftblock.runAction(SKAction.animateWithTextures(reversedLeftArray, timePerFrame: 0.03, resize: true, restore: false))
        case self.rightblock:
            println("openright")
            rightblock.runAction(SKAction.animateWithTextures(reversedRightArray, timePerFrame: 0.03, resize: true, restore: false))
        default: break
        }
    }
}

1 个答案:

答案 0 :(得分:0)

屏幕左侧的触摸意味着x coordinate of the location of the touch将小于width / 2。而对于右侧, x coordinate of the location of the touch将大于width / 2

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {

   for touch in touches {

        let touchPoint = touch.locationInView(self.view)

        let middleOfScreen = (self.view?.frame.width)! / 2

        print(self.frame)

        print(middleOfScreen)
        print(touchPoint)

        if touchPoint.x < middleOfScreen {
            print("Clicked Left Side");
        } else {
            print("Clicked Right Side");
        }
    }
}