gpt4 book ai didi

c++ - 使用旋转矩阵旋转三角形 - 从窗口中消失

转载 作者:行者123 更新时间:2023-11-28 04:10:49 24 4
gpt4 key购买 nike

我尝试使用旋转矩阵围绕其中心顺时针旋转三角形。但是,三角形会移出屏幕并移向左下角。这是我的代码

class Triangle {
public:
vector<glm::vec3> verts; // positions of the triangles vertices.
glm::vec3 pos; // position of the triangle's origin.

void rotate(float rotationMat[4]) {
// Transform vert 1
glm::vec3 vert1 = verts[0]; // Get the vertices (centred about the triangle origin)
vert1 = vert1 - pos; // Get the vertices centered about the origin (0, 0)
// Rotate the vertices
vert1.x = (vert1.x * rotationMat[0]) + (vert1.y * rotationMat[1]);
vert1.y = (vert1.x * rotationMat[2]) + (vert1.x * rotationMat[3]);
// Get the vertices centered about the triangle origin
vert1 = vert1 + pos;

// Set the new vertices value
verts[0] = vert1;



// Transform vert2
glm::vec3 vert2 = verts[1]; // Get the vertices (centered about the triangle origin)
vert2 = vert2 - pos; // Get the vertices centered about the origin (0, 0)
// Rotate the vertices
vert2.x = (vert2.x * rotationMat[0]) + (vert2.y * rotationMat[1]);
vert2.y = (vert2.x * rotationMat[2]) + (vert2.x * rotationMat[3]);
// Get the vertices centered about the triangle origin
vert2 = vert2 + pos;

// Set the new vertices value
verts[1] = vert2;



// Transform vert3
glm::vec3 vert3 = verts[2]; // Get the vertices (centered about the triangle origin)
vert3 = vert3 - pos; // Get the vertices centered about the origin (0, 0)
// Rotate the vertices
vert3.x = (vert3.x * rotationMat[0]) + (vert3.y * rotationMat[1]);
vert3.y = (vert3.x * rotationMat[2]) + (vert3.x * rotationMat[3]);
// Get the vertices centered about the triangle origin
vert3 = vert3 + pos;

// Set the new vertices value
verts[2] = vert3;

}
};

我这样调用方法:

float rotationMat[4] = { (float) cos(1), (float) -sin(1), (float) sin(1), (float) cos(1)};
triangle.rotate(rotationMat);

作为测试,我打印出旋转前后的顶点,结果如下:

BEFORE: 
(100,-100)
(0,100)
(-100,-100)

AFTER:
(788.762,899.003)
(566.437,591.801)
(680.701,749.688)

我哪里错了?为什么三角形会飞出屏幕?

最佳答案

你不能那样做:

vert1.x = (vert1.x * rotationMat[0]) + (vert1.y * rotationMat[1]);
vert1.y = (vert1.x * rotationMat[2]) + (vert1.x * rotationMat[3]);

在第一行之后,vert1.x 将发生变化,您在第二行所做的计算将无效。做:

auto newx = (vert1.x * rotationMat[0]) + (vert1.y * rotationMat[1]);
auto newy = (vert1.x * rotationMat[2]) + (vert1.x * rotationMat[3]);
vert1.x = newx;
vert1.y = newy;

(可能还有其他问题)

关于c++ - 使用旋转矩阵旋转三角形 - 从窗口中消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57828682/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com