2012-03-23 72 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本身不受转型的影响吗?