SpriteKit - touchesMoved,瞄准十字准线

时间:2015-03-01 11:09:46

标签: swift sprite-kit touchesmoved

我有一个spritenode和一个十字准线节点,我希望当玩家触摸spritenode并移动十字准线时也会移动。

  override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {

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


            var body = self.nodeAtPoint(location)

            if var name: String = body.name {

                if body.name == "aim-button" {

                    crossHair.position = CGPointMake(crossHair.position.x + 10, crossHair.position.y + 10)
                }

            }

        }
    }

十字准线确实在一个方向上移动,但我不知道如何根据触摸移动到的空间使其准确(这显然小于十字线应该在屏幕上实际移动的距离) )和方向。

1 个答案:

答案 0 :(得分:2)

    for touch: AnyObject in touches {
        //Get the current position in scene of the touch.
        let location = touch.locationInNode(self)
        //Get the previous position in scene of the touch.
        let previousLocation = touch.previousLocationInNode(self)
        //Calculate the translation.
        let translation = CGPointMake(location.x - previousLocation.x, location.y - previousLocation.y)
        //Get the current position in scene of the crossHair.
        let position = crossHair.position
        // Get the bode touched
        var body = self.nodeAtPoint(location)

        if var name: String = body.name {

            if body.name == "aim-button" {

                //Set the position of the crosshair to its current position plus the translation.
                crossHair.position =  CGPointMake(position.x + translation.x * 2, position.y + translation.y * 2)
                //Set the position of the body
                body.position = location
            }
        }
    }    

如果十字准线移动距离比触摸更远,只需将平移乘以一个因子(我在上面的示例中使用2)。