Node rotation doesn't follow a finger

假装没事ソ 提交于 2019-12-05 07:04:25

问题


I'm trying to rotate an arrow to follow a finger movement but it performs weirdly. It is definitely not following it. I'm trying to do it in touchesMoved. I tried to do this:

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)

    }
}

And also tried this:

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
}

I also tried SKConstraint.orientToPoint but had no luck in it either. What am I doing wrong? Every answer to similar question is suggestion atan2, but it doesn't seem to work for me.


回答1:


If you want to rotate the sprite towards to touch location, it should be simple as :

    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

It worked when I tried, so it can give you an basic idea where to start. Or I misunderstood what you are trying to achieve...

EDIT:

Currently what you will get if you try to convert angle to degrees is angle in range from -90 to 270 degrees. Its described here why. If you want to work with angle in range of 0 to 360, you can change to code above to:

    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

Here is the result with debugging data:



来源:https://stackoverflow.com/questions/32417157/node-rotation-doesnt-follow-a-finger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!