【问题标题】:iOS Math for a turret/cannon that rotates to follow a finger用于旋转以跟随手指的炮塔/大炮的 iOS 数学
【发布时间】:2012-03-23 22:37:30
【问题描述】:

我试图找出旋转 UIView 的数学运算,当在屏幕上移动时,某一侧总是“跟随”手指。

我快到了,但我已经好几年没学过三角学了,我也不知道该怎么做。这是我所拥有的:

-(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);
}

【问题讨论】:

  • 如果这有帮助,Ray Wenderlich 写了关于旋转炮塔的文章。它在 cocos2d 中,但我认为在普通的旧 objc 中有很多相似之处:raywenderlich.com/692/rotating-turrets
  • 您当前的解决方案与您希望实现的解决方案有何不同? atan2 是用于即时跟踪的最简单的方法,因此您看起来几乎已经弄清楚了。
  • 这不是完全正确的。它在某些地方显得很突出,当我保持 X 值不变并上下移动 Y 时,它会使 UIView 移动太多。

标签: objective-c ios ios5 uiview trigonometry


【解决方案1】:

首先,感谢所有花时间回答的人!

我玩了一段时间,似乎唯一的问题是我使用ints 代替dydx 而不是floats。我还找到了一种将度数转换为弧度的漂亮、快速的“方法”。这是最终的工作代码:

#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));
}

【讨论】:

    【解决方案2】:

    我假设你的炮塔初始航向是正确的。

    您的 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);
    }
    

    我认为它可以更优化(否),但我暂时无法测试自己。好用吗?

    【讨论】:

    • 这只是糟糕地重新实现了atan2
    【解决方案3】:

    您的常数 135 可能不正确,因为 atan2CGAffineTransformMakeRotation 都以弧度而不是度数工作。 135度的弧度当量是π·3/4。

    但是,除此之外,您的代码看起来还不错——这应该只是导致一个恒定的偏移量,而不是您描述的奇怪行为。您确定cannon.frame.origin 本身不受转换的影响吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多