如何将atan2()映射到0-360度 [英] How to map atan2() to degrees 0-360

查看:856
本文介绍了如何将atan2()映射到0-360度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

atan2(y,x)在180°处具有不连续性,在顺时针方向上切换为-180°..0°.

atan2(y,x) has that discontinuity at 180° where it switches to -180°..0° going clockwise.

如何将值的范围映射到0°..360°?

How do I map the range of values to 0°..360°?

这是我的代码:

CGSize deltaPoint = CGSizeMake(endPoint.x - startPoint.x, endPoint.y - startPoint.y);
float swipeBearing = atan2f(deltaPoint.height, deltaPoint.width);

在给定startPoint和endPoint这两个XY点结构的情况下,我正在计算滑动触摸事件的方向.该代码适用于iPhone,但是支持atan2f()的任何语言都可以.

I'm calculating the direction of a swiping touch event given the startPoint and endPoint, both XY point structs. The code is for the iPhone but any language that supports atan2f() will do.

感谢您的帮助人员,提供了常规解决方案和代码.

Thanks for your help guys, with both the general solution and code.

更新:我把erikkallen的答案变成了一个具有很好的长变量名的函数,所以我将在6个月后理解它.也许会帮助其他一些iPhone新手.

Update: I made erikkallen's answer into a function with nice long variable names so I'll comprehend it 6 months from now. Maybe it will help some other iPhone noob.

float PointPairToBearingDegrees(CGPoint startingPoint, CGPoint endingPoint)
{
    CGPoint originPoint = CGPointMake(endingPoint.x - startingPoint.x, endingPoint.y - startingPoint.y); // get origin point to origin by subtracting end from start
    float bearingRadians = atan2f(originPoint.y, originPoint.x); // get bearing in radians
    float bearingDegrees = bearingRadians * (180.0 / M_PI); // convert to degrees
    bearingDegrees = (bearingDegrees > 0.0 ? bearingDegrees : (360.0 + bearingDegrees)); // correct discontinuity
    return bearingDegrees;
}

推荐答案

(x > 0 ? x : (2*PI + x)) * 360 / (2*PI)

这篇关于如何将atan2()映射到0-360度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆