swift - SpriteKit - touchesMoved,瞄准十字准线

标签 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)
                }

            }

        }
    }

十字准线确实会移动,但只能在一个方向上移动,我不知道如何根据触摸移动到的空间使其准确(这显然比十字准线在屏幕上实际移动的空间小得多) 和方向。

最佳答案

    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)。

关于swift - SpriteKit - touchesMoved,瞄准十字准线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28792842/

相关文章:

swift - 将 SKEmitterNode 设置为背景

ios - 如果松开第一个手指,UIView touchesMoved 不会被调用

ios - 如何在 Swift 中为我的旋转圆做一个 if 语句?

ios - 请帮助我正确应用设备旋转数据

swift - 如何用固定的开始到结束位置替换 panGestureDidMove

ios - SpriteKit - 使某些 SpriteNodes 在不禁用其物理体的情况下不会发生碰撞

iPhone 多点触控 - 一些触摸调度 touchesBegan : but not touchesMoved:

ios - 将新用户插入 firebase

ios - 如何以编程方式创建 UIImage View - Swift

iOS - 基于设备的不同图像或缩放相同的图像?