2012-03-23 129 views
0

我想弄清楚旋轉一個UIView的數學某個邊總是「跟隨」一個手指,當在屏幕上移動。iOS數學炮塔/大炮旋轉跟隨一個手指

我幾乎在那裏,但我沒有三角幾年,我不知道該怎麼做。這是我得到的:

-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [touches anyObject]; 
    CGPoint touchPoint = [touch locationInView:self.view]; 

    int dy = cannon.frame.origin.y - touchPoint.y; 
    int dx = cannon.frame.origin.x - touchPoint.x; 

    cannon.transform = CGAffineTransformMakeRotation(atan2(dy,dx) - 135); 
} 
+1

如果這有幫助,Ray Wenderlich寫了關於旋轉炮塔。它在cocos2d中,但我認爲在普通的舊objc中有很多相似之處:http://www.raywenderlich.com/692/rotating-turrets – CodaFi 2012-03-23 22:47:53

+0

你目前的解決方案與你想要發生的不同之處是什麼? 'atan2'是用於即時追蹤的最簡單的東西,所以你看起來就像你已經弄清楚了。 – Tommy 2012-03-23 22:50:13

+0

這並不完全正確。它在某些地方出現鬆動,當我保持X值不變並上下移動Y時,它會過度移動UIView。 – Derek 2012-03-23 22:56:48

回答

1

首先,謝謝大家花時間回答!

我用它玩了一段時間,它似乎是唯一的問題是,我用int S表示dydx,而不是float秒。我還發現了一個漂亮的,快速的「方法」,用於將度數轉換爲弧度。這是最後的工作代碼:

#define DEGREES_TO_RADIANS(angle) (angle/180.0 * M_PI) 

-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [touches anyObject]; 
    CGPoint touchPoint = [touch locationInView:self.view]; 

    float dy = cannon.frame.origin.y - touchPoint.y; 
    float dx = cannon.frame.origin.x - touchPoint.x; 

    cannon.transform = CGAffineTransformMakeRotation(atan2(dy,dx) - DEGREES_TO_RADIANS(90)); 
} 
0

我假設你的炮塔初始標題是正確的。

你PI常數爲3.14(以弧度角)

-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [touches anyObject]; 
    CGPoint touchPoint = [touch locationInView:self.view]; 

    int dy = cannon.frame.origin.y - touchPoint.y; 
    int dx = cannon.frame.origin.x - touchPoint.x; 

    float a = atan(abs(dy)/abs(dx)); 
    if(dx>0 && dy<0) a += PI/2; 
    if(dx<0 && dy<0) a += PI; 
    if(dx<0 && dy>0) a += 3*PI/2; 

    cannon.transform = CGAffineTransformMakeRotation(a); 
} 

我認爲這可能是更優化的(如果沒有),但我無法測試自己的時刻。它有效嗎?

+0

這只是重新實現'atan2'糟糕。 – 2012-03-24 00:40:46

+0

如何!不知道atan2 ...很酷 – Martin 2012-03-24 17:52:56

0

您的常數135可能不正確,因爲atan2CGAffineTransformMakeRotation都以弧度而非度數工作。 135度的弧度等於π·3/4。

但是,除此之外,你的代碼看起來很好 - 這應該只是導致一個常量偏移量,而不是你描述的奇怪行爲。您確定cannon.frame.origin本身不受轉型的影響嗎?