旋转 2D 正方形
Rotating 2D square
我可以旋转3D对象,但它似乎不适用于2D对象。
我想将可移动(通过箭头)正方形向右旋转 90 度(旋转中心:正方形的中心)。我想出了以下代码:
class CSquare : public CObject {
SPoint pnta; //left top corner of a square
uint16 len; //length
bool bFill, bRotate; //filled? rotating?
GLubyte color[4]; //filling color
float angle; //rotate for this
public:
CSquare();
CSquare(const CSquare &sqr);
CSquare(SPoint &a, uint16 l, bool fill = false);
CSquare(uint16 x, uint16 y, uint16 l, bool fill = false);
void draw();
void toggleRotate();
void setColor(GLubyte r, GLubyte g, GLubyte b, GLubyte a);
void setPoint(uint16 x, uint16 y);
SPoint getPoint();
uint16 getPosX();
uint16 getPosY();
uint16 getLength();
};
void CSquare::draw() {
glPushMatrix();
if (bRotate)
if (++angle < 360.0f)
{
glTranslatef(pnta.nX + len/2, pnta.nY + len/2, 0);
glRotatef(90, 0, 0, 1);
}
else angle = 0.0f;
if (bFill == true) glBegin(GL_QUADS);
else glBegin(GL_LINE_LOOP);
glColor4ubv(color);
glVertex2i(pnta.nX, pnta.nY);
glColor4ub(255, 255, 0, 0); //temporary to visualise rotation effect
glVertex2i(pnta.nX + len, pnta.nY);
glColor4ub(0, 255, 0, 0);
glVertex2i(pnta.nX + len, pnta.nY + len);
glColor4ub(0, 0, 255, 0);
glVertex2i(pnta.nX, pnta.nY + len);
glEnd();
glPopMatrix();
}
我的代码在某种程度上有效:它确实旋转对象,但不在所需点的中心。
附言。如果需要,我可以上传完整的应用程序(Visual Studio 2010 Project,使用 FreeGLUT 和 SDL)。
我假设你实际上并没有以固定的角度旋转: glRotatef(90, 0, 0, 1);
如果这不是转录错误,您应该先修复它。
也就是说,旋转总是围绕原点发生。 你在(pnta.nX, pnta.nY)
画你的形状。 您似乎想围绕形状的中心旋转。 为此,您必须首先将该点移动到原点。 然后执行旋转,然后将点移回所需位置:
glPushMatrix();
glTranslatef(pnta.nX + len/2, pnta.nY + len/2, 0);
glRotatef(angle, 0, 0, 1);
glTranslatef(-pnta.nX - len/2, -pnta.nY - len/2, 0);
drawShape();
glPopMatrix();
默认情况下,我们经常使用几何图形以原点为中心的对象进行建模。 这样,我们可以简单地旋转对象,然后将其参考点转换为我们想要的位置。
相关文章:
- 2D数组来自文本输入,中间有空格
- 将值指定给向量(2D)的向量中的某个位置
- 试试完美的正方形,你能给点小费吗
- 如何使用用户输入在C++中正确填充2D数组
- 如何在C++中检查2D数组中负值的输入验证
- 当我在main中声明了我的2d数组时,为什么我的程序会退出
- 在 2D 向量中使用第三个 [ ] 有什么意义?
- 四边形的 2D 旋转
- 打印第二列时的2d字符矢量打印空间
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 如何在C++函数中声明静态 2D 数组?
- 我是 C++ 的初学者,我想知道如何在 2D 矢量中获取重复值
- 如何声明一个可以在整个程序中使用的全局 2d 3d 4d .. 数组(堆版本)变量?
- opengl glBegin(GL_LINES) 和 glBegin(GL_POINT) 在 2D 中不可视化点矢量
- 在C++中迭代 2D 容器的最干净方法
- 如何引用 2D 指针?
- 如何在 C++ 中使用它的构造函数初始化 unique_ptrs 的 2D 向量?
- 旋转 2D 正方形
- 是否有一个c++源/lib来解决2D Bin Packing使用矩形Bin(而不是正方形)和旋转
- 使用c++在opengl中创建正方形网格(2D)