计算两点之间角度的缺陷

时间:2011-12-13 17:25:52

标签: cocos2d-iphone trigonometry

我有一些代码可以很好地找到两个点tempnewpoint之间的角度:

        CGPoint newpoint=CGPointMake(newX,newY );        
        CGPoint diff = ccpSub(temp.position, newpoint);
        float rads = atan2f( diff.y, diff.x);
        float degs = CC_RADIANS_TO_DEGREES(rads);

               CCLOG(@"now: %f,%f to:%f,%f degs:%f",temp.position.x,temp.position.y,newX,newY,degs);

它在大多数情况下都正常工作,但对于某些点它有错误。这是日志的一部分:

2011-12-13 11:05:19.401 Bells[2303:c503] now: 368.603271,147.813110 to:265.566284,210.476471 degs:-30.655481
2011-12-13 11:05:20.417 Bells[2303:c503] now: 77.030159,167.413544 to:184.491669,117.072098 degs:154.254135
2011-12-13 11:05:20.417 Bells[2303:c503] now: 355.119720,121.963585 to:307.802826,49.591988 degs:56.634174
2011-12-13 11:05:20.418 Bells[2303:c503] now: 465.000000,89.771843 to:373.258270,15.000000 degs:39.249508
2011-12-13 11:05:20.419 Bells[2303:c503] now: 307.277588,69.095749 to:363.791168,174.386093 degs:-118.026299
2011-12-13 11:05:21.417 Bells[2303:c503] now: 190.993607,194.947479 to:101.720551,255.007492 degs:-33.194214
2011-12-13 11:05:21.418 Bells[2303:c503] now: 23.930172,27.319054 to:85.588303,15.000000 degs:167.615768
2011-12-13 11:05:21.418 Bells[2303:c503] now: 365.033630,218.904007 to:277.799194,141.605042 degs:41.585751
2011-12-13 11:05:21.419 Bells[2303:c503] now: 221.239227,153.457306 to:116.308037,87.374733 degs:32.344673
2011-12-13 11:05:22.433 Bells[2303:c503] now: 140.302948,260.575500 to:191.313812,208.167419 degs:133.118576
2011-12-13 11:05:22.433 Bells[2303:c503] now: 16.781921,224.473648 to:90.456161,153.657745 degs:135.340363
2011-12-13 11:05:22.434 Bells[2303:c503] now: 307.802826,49.591988 to:391.818512,15.000000 degs:156.793350
2011-12-13 11:05:22.435 Bells[2303:c503] now: 265.566284,210.476471 to:311.953583,114.193481 degs:115.011368
2011-12-13 11:05:22.435 Bells[2303:c503] now: 140.599457,296.268768 to:39.459061,305.000000 degs:-4.328590
2011-12-13 11:05:22.436 Bells[2303:c503] now: 459.438629,190.859222 to:465.000000,96.320923 degs:92.733452

这一行特别是问题的一个例子:

2011-12-13 11:05:21.418 Bells[2303:c503] now: 23.930172,27.319054 to:85.588303,15.000000 degs:167.615768

这两点之间的距离非常接近水平,因此您可以期望一个准水平的角度。然而,角度几乎是垂直的。我不是三角形的高手,但显然有一个数学问题只影响了一些点。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

你可以使用ccpAngle(< #CGPoint a#>,< #CGPoint b#>)或ccpAngleSigned(< #CGPoint a#>,< #CGPoint b#>),是的,2点之间有一个角度,一个点是一个向量。

请记住,cocos使用度数和使用CGPoints完成的数学使用Radians。还要记住,cocos顺时针旋转,CGPoints角度是逆时针旋转。

您可以使用建议的助手作为CC_RADIANS_TO_DEGREES