代码之家  ›  专栏  ›  技术社区  ›  Joshua

围绕原点旋转点的正确三角法

  •  14
  • Joshua  · 技术社区  · 15 年前

    以下方法中的任何一种是否使用正确的数学来旋转一个点?如果是,哪一个是正确的?

    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;
    }
    
    3 回复  |  直到 15 年前
        1
  •  22
  •   Beta    15 年前

    这取决于你如何定义 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;
    
        2
  •  27
  •   Community CDub    8 年前

    wikipedia的

    要使用矩阵进行旋转,将要旋转的点(x,y)写为矢量,然后乘以从角度计算的矩阵,如:

    其中(x_2,y_2)是旋转后点的坐标,x_2和y_2的公式可以看出:

    方格要旋转的点(x,y)写为一个矢量,然后乘以从角度计算出的矩阵,如:

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

    其中(x_2,y_2)是旋转后点的坐标,x_2和y_2的公式可以看出:

    alt text

        3
  •  1
  •   YeenFei    15 年前

    这是从我自己的向量库中提取的。

    //----------------------------------------------------------------------------------
    // 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;
    }