2015-09-05 51 views
1

我試圖旋轉箭頭來跟隨手指移動,但它執行奇怪。絕對不會跟着它。我試圖在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

如果你想旋轉精靈對對碰的位置,應該是簡單的:

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

+0

是的,它的工作!我不知道爲什麼我會遇到麻煩:-)謝謝! – Burundanga

+0

@Whirlwind計算應該是'dx = touchLocation.x - hero.position.x','dy = touchLocation.y - hero.position.y'和'let angle = atan2(dy,dx) - CGFloat(M_PI_2 )' – Epsilon

+0

@Epsilon根據文檔,分配給zRotation屬性的正值表示逆時針旋轉。這是我發佈的視頻中可以看到的。我很確定你和我的例子有完全相同的效果,但如果你不同意,你能澄清一下這個區別嗎? – Whirlwind