使用旋转矩阵按中心旋转正方形

Rotation of square by center using rotation matrix

我正在尝试通过此实现使用旋转矩阵来旋转正方形。

void Square::rotateVertices(std::vector<float> &vertices)
{
   float px = (vertices[0]+vertices[2])/2;
   float py = (vertices[1]+vertices[5])/2;        
   for (int i = 0; i < 4; i++)
   {
       float x1 = vertices[i*2];
       float y1 = vertices[i*2+1];
       vertices[i * 2] = px + (x1 -px)*cos(angle) - (y1 -py)*sin(angle);
       vertices[(i * 2) + 1] = py + (x1 -px)*sin(angle) + (y1 -py)*cos(angle);
    }
}

使用以下代码计算顶点:

float ay = (size / float(height) / 2.f), ax = (size / float(width) / 2.f);
std::vector<float> vertices = {
            2 * (((x) - float(width) / 2) / float(width)) - ax, 2 * ((y - float(height)) / float(height)) - ay + 1.0f,
            2 * (((x) - float(width) / 2) / float(width)) + ax, 2 * ((y - float(height)) / float(height)) - ay + 1.0f,
            2 * (((x) - float(width) / 2) / float(width)) + ax, 2 * ((y - float(height)) / float(height)) + ay + 1.0f,
            2 * (((x) - float(width) / 2) / float(width)) - ax, 2 * ((y - float(height)) / float(height)) + ay + 1.0f};
rotateVertices(vertices);

其中:

angle=0 的计算正方形看起来很正常,但当我检查时,即。 angle=M_PI/4应该旋转正方形45度,旋转应用正方形到矩形的奇怪变换。(如图所示)

我当然希望保持比例不变,但我暂时想不出解决办法。如果有人能想到快速修复,或者能指出正确的方向,我会很高兴。

那是因为你的正方形 一个长方形。我的 crystal 球知道这一点,因为它的宽度和高度是分开计算的,因此,你的意思是让它们不同:

// if you wanted these to be the same you wouldn't calculate them separately
float ay = (size / float(height) / 2.f), ax = (size / float(width) / 2.f);

它看起来像正方形的唯一原因是因为屏幕投影也被扭曲以抵消它。

当您旋转矩形时,它们不再相互抵消。

你应该画一个相同宽度和高度的正方形,然后固定将正方形转换为屏幕坐标的矩阵,这样当你渲染相同宽度和高度的东西时它确实得到相同的宽度和高度在屏幕上。