节点旋转不跟随手指

时间:2015-09-05 19:59:27

标签: ios rotation sprite-kit

我试图旋转箭头以跟随手指移动,但它表现奇怪。它肯定不会跟随它。我试图在touchesMoved中做到这一点。我试着这样做:

var fingerLocation = CGPoint()

override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
    for touch: AnyObject in touches {
        fingerLocation = touch.locationInNode(self)
        let currentOrient = arrow.position
        let angle = atan2(currentOrient.y - fingerLocation.y, currentOrient.x - fingerLocation.y)
        let rotateAction = SKAction.rotateToAngle(angle + CGFloat(M_PI*0.5), duration: 0.0)

        arrow.runAction(rotateAction)

    }
}

还试过这个:

var fingerLocation = CGPoint()

override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
    for touch: AnyObject in touches {
        fingerLocation = touch.locationInNode(self)
}
override func update(currentTime: CFTimeInterval) {
    /* Called before each frame is rendered */
   var radians = atan2(fingerLocation.x, fingerLocation.y)
    arrow.zRotation = -radians
}

我也尝试过SKConstraint.orientToPoint,但也没有运气。我究竟做错了什么?类似问题的每个答案都是建议atan2,但它似乎对我没有用。

1 个答案:

答案 0 :(得分:1)

如果你想将精灵旋转到触摸位置,它应该很简单:

    let touchLocation = touch.locationInNode(self)

    var dx =  hero.position.x - positionInScene.x;
    var dy = hero.position.y - positionInScene.y  ;

    var angle = atan2(dy,dx) + CGFloat(M_PI_2)

    hero.zRotation = angle

当我尝试时它起作用,所以它可以给你一个基本的想法从哪里开始。或者我误解了你想要实现的目标......

编辑:

目前,如果您尝试将角度转换为度数,您将得到的角度范围为-90到270度。它描述了here为什么。如果要使用0到360范围内的角度,可以将上面的代码更改为:

    var dx = missile.position.x - positionInScene.x ;
    var dy = missile.position.y  - positionInScene.y;

    var angleInRadians = atan2(dy,dx) + CGFloat(M_PI_2)

    if(angleInRadians < 0){
        angleInRadians = angleInRadians + 2 * CGFloat(M_PI)
    }

    missile.zRotation = angleInRadians

    var degrees = angleInRadians < 0 ? angleInRadians * 57.29577951 + 360 :  angleInRadians * 57.29577951

以下是调试数据的结果:

enter image description here