Swift,Spritekit旋转精灵swift 3

时间:2016-12-16 16:14:54

标签: ios swift sprite-kit

我正在尝试使用swift,IOS 10和touchesmoved函数旋转一个精灵,我运行的代码实际上它移动了精灵,但方法不正确,方向错误等。

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
   super.touchesMoved(touches, with: event)
   guard let touch=touches.first{
         return
   }
   let touchLocation = touch.location(in: self)
   self.zRotation=CGFloat(atan2(Double(touchLocation.y), Double(touchLocation.x)))
}

有没有人知道使用zRotation和touchesMoved旋转精灵的正确方法? 谢谢

2 个答案:

答案 0 :(得分:1)

我认为你可能忽视了SpriteKit中限制的强大力量。这很容易做到,Apple在推广,展示和教育那些考虑使用SpriteKit的人方面做得非常糟糕。

Constraints允许你说&#34;去这里&#34;,或者&#34;看看这个&#34;。

在你的情况下,&#34;看看这个&#34;从文档来看是理想的:

方向约束

  

定向约束的一个常见用途是进行观察   约束。例如,您可以创建一个look-at约束来创建   一双眼睛跟着一个移动的物体或者有一个火箭点   目标的方向。

更具体地说,您可以在touchesMoved中使用这些:

https://developer.apple.com/reference/spritekit/skconstraint/1519627-orient

答案 1 :(得分:0)

感谢所有的建议。是的,我对问题的解释并不太好。所以这里会添加完整的代码,当我停止拖动并再次开始拖动时,它似乎偶尔会自动移动90度

我试图做的是围绕另一个精灵旋转一个精灵,例如围绕它的轮子的炮筒......当从场景加载轮子时,它调用这个类并添加一个子节点(桶)能够绕着它的轮子移动

import SpriteKit
class WheelNode: SKSpriteNode, CustomNodeEvent{
  private var tubeNode=SKSpriteNode(imageNamed: "cannon-barrel")
  var previousPoint:CGPoint!
  var touchLocation:CGPoint!
  func didMoveToScene() {
    guard let scene=scene else{
        return
    }
    isUserInteractionEnabled=true
    tubeNode.anchorPoint=CGPoint(x:0, y:0)
    tubeNode.position=position
    self.addChild(tubeNode)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch=touches.first{
            previousPoint=touch.location(in: scene!)
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesMoved(touches, with: event)
        if let touch=touches.first{
            touchLocation=touch.location(in: scene!)
            var angle=atan2(touchLocation.y-previousPoint.y, touchLocation.x-previousPoint.x)
            self.zRotation=angle
        }
    }
}