opengl 用旋转矩阵求正方形的圆心旋转

h9a6wy2h  于 2022-11-04  发布在  其他
关注(0)|答案(1)|浏览(149)

我试图用这个实现的旋转矩阵来旋转一个正方形。

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);

其中:

  • width -窗口宽度
  • 高度-窗口高度
  • size -正方形的大小

计算后的正方形看起来正常的angle=0,但当我已经检查了即angle=M_PI/4这应该旋转正方形45度,旋转适用于奇怪的变换正方形到矩形。(如图所示)x1c 0d1x
当然,我很想保持这个比例,但我现在想不出解决办法。如果有人能想到快速解决办法,或者能给我指出正确的方向,我会很高兴。

9lowa7mx

9lowa7mx1#

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

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

它看起来像正方形的唯一原因是因为屏幕投影也被扭曲以抵消它。
当旋转矩形时,它们不再抵消。
您应该绘制一个具有相同宽度和高度的正方形,然后修复将正方形转换为屏幕坐标的矩阵,以便当您渲染具有相同宽度和高度的对象时,它在屏幕上的宽度和高度也相同。

相关问题