【问题标题】:Angle between two lines is wrong两条线之间的角度是错误的
【发布时间】:2011-09-14 14:50:19
【问题描述】:

我想得到两条线之间的角度。 所以我使用了这段代码。


int posX = (ScreenWidth) >> 1;

int posY = (ScreenHeight) >> 1;

double radians, degrees;

radians = atan2f( y - posY , x - posX);

degrees = -CC_RADIANS_TO_DEGREES(radians);

NSLog(@"%f %f",degrees,radians);

但它不起作用。 日志是:146.309935 -2.553590

怎么了? 我不知道原因。 请帮帮我。

【问题讨论】:

  • 那么垂直线呢,它总是垂直的吗?
  • 我不知道xyScreenWidthScreenHeight 的值,但这似乎是正确的,除了你正在更改值的符号度数。你期待什么结果?
  • 我想得到y轴和直线之间的角度。

标签: objective-c cocos2d-iphone


【解决方案1】:

如果你只是使用

radians = atan2f( y - posY , x - posX);

你会得到与水平线y=posY的角度(蓝色角度)。

您需要将M_PI_2 添加到您的弧度值以获得正确的结果。

【讨论】:

  • 请详细说明。
  • 我编辑了你的图片。您正在计算蓝色角度而不是红色角度。
【解决方案2】:

这是我使用的一个函数。它对我很有用...

float cartesianAngle(float x, float y) {
    float a = atanf(y / (x ? x : 0.0000001));
    if      (x > 0 && y > 0) a += 0;
    else if (x < 0 && y > 0) a += M_PI;
    else if (x < 0 && y < 0) a += M_PI;
    else if (x > 0 && y < 0) a += M_PI * 2;
    return a;
}

编辑:经过一些研究,我发现您可以使用 atan2(y,x)。大多数编译器库都有这个功能。你可以忽略我上面的函数。

【讨论】:

    【解决方案3】:

    如果您有 3 个点并且想要计算它们之间的角度,这里是一种快速且正确的计算直角值的方法:

    double AngleBetweenThreePoints(CGPoint pointA, CGPoint pointB, CGPoint pointC)
    {
        CGFloat a = pointB.x - pointA.x;
        CGFloat b = pointB.y - pointA.y;
        CGFloat c = pointB.x - pointC.x;
        CGFloat d = pointB.y - pointC.y;
    
        CGFloat atanA = atan2(a, b);
        CGFloat atanB = atan2(c, d);
    
        return atanB - atanA;
    } 
    

    如果您在其中一条线上指定点、交点和另一条线上的点,这将适用于您。

    【讨论】:

    • 不应该对atan2() 的调用指定atan2(Δy, Δx),从而指定atan2(b, a)atan2(d, c)
    猜你喜欢
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多