2010-07-02 79 views
14

以下两种方法中的哪一种使用正确的数学来旋转点?如果是这样,哪一个是正确的?适当的三角法旋转原点的位置

POINT rotate_point(float cx,float cy,float angle,POINT p) 
{ 
    float s = sin(angle); 
    float c = cos(angle); 

    // translate point back to origin: 
    p.x -= cx; 
    p.y -= cy; 

    // Which One Is Correct: 
    // This? 
    float xnew = p.x * c - p.y * s; 
    float ynew = p.x * s + p.y * c; 
    // Or This? 
    float xnew = p.x * c + p.y * s; 
    float ynew = -p.x * s + p.y * c; 

    // translate point back: 
    p.x = xnew + cx; 
    p.y = ynew + cy; 
} 
+10

我不很明白。什么是cx和cy?另外,你已经声明了你的POINT类型的函数,但是它不返回一个POINT,或者其他任何东西。 – 2010-07-02 01:09:06

+1

@Brian Hooper:+1用于指出有意义的变量名称的好处;) – Cogwheel 2010-07-02 04:43:02

回答

22

这取决于你如何定义angle。如果是逆时针测量(这是数学约定),那么正确的旋转是你的第一个:

// This? 
float xnew = p.x * c - p.y * s; 
float ynew = p.x * s + p.y * c; 

但如果是顺时针测量,然后第二个是正确的:

// Or This? 
float xnew = p.x * c + p.y * s; 
float ynew = -p.x * s + p.y * c; 
27

From Wikipedia

要使用的矩阵的点(x,y)与被旋转被写为一个向量,然后通过从角度计算,θ,像这样的矩阵相乘进行旋转:

https://upload.wikimedia.org/math/0/e/d/0ed0d28652a45d730d096a56e2d0d0a3.png

其中(x',y')的是旋转后的点的坐标,并且x的公式'和y'可以被看作是

alt text

+0

不要忘记,如果你在一个典型的屏幕坐标空间中工作,那么你的y轴将从数学标准中倒过来+ y,up是-y),你需要考虑这一点。 – 2017-11-08 20:13:28

1

这是从我自己的矢量库中提取..

//---------------------------------------------------------------------------------- 
// Returns clockwise-rotated vector, using given angle and centered at vector 
//---------------------------------------------------------------------------------- 
CVector2D CVector2D::RotateVector(float fThetaRadian, const CVector2D& vector) const 
{ 
    // Basically still similar operation with rotation on origin 
    // except we treat given rotation center (vector) as our origin now 
    float fNewX = this->X - vector.X; 
    float fNewY = this->Y - vector.Y; 

    CVector2D vectorRes( cosf(fThetaRadian)* fNewX - sinf(fThetaRadian)* fNewY, 
          sinf(fThetaRadian)* fNewX + cosf(fThetaRadian)* fNewY); 
    vectorRes += vector; 
    return vectorRes; 
} 
+2

您可以将'cosf'和'sinf'结果保存到变量中,以使用三分之一的trig函数调用。 :) – 2010-07-02 01:28:13

+0

好抓..... – YeenFei 2010-07-02 01:31:53