用户触摸时检测圆圈中的度数

时间:2015-12-12 16:47:24

标签: ios swift skspritenode

我希望创建一个swift函数来返回用户触摸图像(SKSpritenode)的度数(Float)。在touchesBegan中,我知道如何检测x&我的形象的位置。我们的想法是创建一个接受这些位置并返回度数的函数。

修订 - 以下代码现在可以使用:

    class GameScene: SKScene {
override func didMoveToView(view: SKView) {
    /* Setup your scene here */

   self.anchorPoint = CGPointMake(0.5, 0.5)
   myNode.position = CGPointMake(0, -myNode.frame.height / 2)
   self.addChild(myNode)

}


override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
   /* Called when a touch begins */

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


            if myNode.containsPoint(location) {
            print("tapped!")
            let origin = myNode.position
            let touch = touch.locationInNode(myNode.parent!)
            let diffX = touch.x - origin.x
            let diffY = touch.y - origin.y
            let radians = atan2(diffY, diffX)
            let degrees = radians * CGFloat(180 / M_PI)

            print("degrees = \(degrees)") 

        }

    }
}

1 个答案:

答案 0 :(得分:2)

您需要将用户的触摸位置与原点进行比较,原点可能是您的精灵节点的中心。这里有一些代码可以帮助您入门:

let origin = CGPoint(x: 0, y: 0)
let touch = CGPoint(x: 100, y: 100)

let diffX = touch.x - origin.x
let diffY = touch.y - origin.y
let radians = atan2(diffY, diffX)
let degrees = radians * CGFloat(180 / M_PI)

如果您想要显示用户信息,那么最后一个值 - degrees - 就是您想要的那个。如果你想做更多的计算,你应该坚持使用radians