计算旋转矩形的顶点

时间:2009-09-24 00:00:20

标签: c++ math matrix trigonometry rectangles

嘿伙计们,我正在尝试计算旋转矩形(2D)的顶点。

如果矩形没有旋转,这很容易,我想出那部分。

如果矩形已旋转,我想到了两种可能的方法来计算顶点。 1)弄清楚如何将顶点从局部/对象/模型空间(我在下面看到的那些)转换为世界空间。老实说,我没有任何线索,如果这是最好的方式,那么如果我能弄明白的话,我觉得我会从中学到很多......

2)使用trig以某种方式确定矩形的端点相对于世界空间中矩形的位置的位置。这是我一直试图做的方式,直到现在,我还没弄明白。

这是迄今为止计算顶点的函数,感谢任何帮助

void Rect::calculateVertices()
{
    if(m_orientation == 0) // if no rotation
    {
        setVertices(
        &Vertex( (m_position.x - (m_width / 2) * m_scaleX), (m_position.y + (m_height / 2) * m_scaleY), m_position.z), 
        &Vertex( (m_position.x + (m_width / 2) * m_scaleX), (m_position.y + (m_height / 2) * m_scaleY), m_position.z),
        &Vertex( (m_position.x + (m_width / 2) * m_scaleX), (m_position.y - (m_height / 2) * m_scaleY), m_position.z),
        &Vertex( (m_position.x - (m_width / 2) * m_scaleX), (m_position.y - (m_height / 2) * m_scaleY), m_position.z) );
    }
    else
    {
        // if the rectangle has been rotated..
    }

    //GLfloat theta = RAD_TO_DEG( atan( ((m_width/2) * m_scaleX) / ((m_height / 2) * m_scaleY) ) );
    //LOG->writeLn(&theta);

}

2 个答案:

答案 0 :(得分:17)

我只想变换每个点,对每个点应用相同的旋转矩阵。如果它是2D平面旋转,它将如下所示:

x' = x*cos(t) - y*sin(t)
y' = x*sin(t) + y*cos(t)

其中(x,y)是原始点,(x',y')是旋转坐标,t是从x轴以弧度测量的角度。旋转是逆时针旋转的。

我的建议是在纸上做一次。绘制一个矩形,计算新坐标,并重新绘制矩形,以便在编码之前确保它是正确的。然后使用此示例作为单元测试,以确保您正确编码。

答案 1 :(得分:2)

我认为你使用atan()在正确的轨道上返回一个角度。但是,您希望将height除以width而不是相反。这将为您提供矩形右上角的默认(未旋转)角度。你应该能够做到这一点:

// Get the original/default vertex angles
GLfloat vertex1_theta = RAD_TO_DEG( atan(
            (m_height/2 * m_scaleY)
            / (m_width/2 * m_scaleX) ) );
GLfloat vertex2_theta = -vertex1_theta; // lower right vertex
GLfloat vertex3_theta = vertex1_theta - 180; // lower left vertex
GLfloat vertex4_theta = 180 - vertex1_theta; // upper left vertex

// Now get the rotated vertex angles
vertex1_theta += rotation_angle;
vertex2_theta += rotation_angle;
vertex3_theta += rotation_angle;
vertex4_theta += rotation_angle;

//Calculate the distance from the center (same for each vertex)
GLfloat r = sqrt(pow(m_width/2*m_scaleX, 2) + pow(m_height/2*m_scaleY, 2));

/* Calculate each vertex (I'm not familiar with OpenGL, DEG_TO_RAD
 * might be a constant instead of a macro)
 */
vertexN_x = m_position.x + cos(DEG_TO_RAD(vertexN_theta)) * r;
vertexN_y = m_position.y + sin(DEG_TO_RAD(vertexN_theta)) * r;

// Now you would draw the rectangle, proceeding from vertex1 to vertex4.
为了清楚起见,显然比必要的更长。当然,使用转换矩阵的duffymo解决方案可能更优雅和高效:)

编辑:现在我的代码应该可行了。我将(width / height)更改为(height / width),并使用矩形中心的恒定半径来计算顶点。在http://pastebin.com/f1c76308c

处使用Python(龟)代码