Reputation: 22006
Let's say that I want to translate a polygon.If before drawing it I use glTranslatef it gets translated, but if I want to draw two polygons and translate only one, how do I do?
#include <OpenGL/OpenGL.h>
#include <GLUT/GLUT.h>
#include "utility.h"
void init()
{
glLoadIdentity();
glOrtho(-1, 1, -1, 1, -1, 1);
}
void render()
{
glClearColor(APPLE_GRAY);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glTranslatef(0.5, 0.0, 0.0);
glBegin(GL_POLYGON);
glColor4f(RED);
glVertex2f(0,0.5);
glVertex2f(-0.5,-0.5);
glVertex2f(0.5, -0.5);
glBegin(GL_POLYGON);
glColor4f(BLUE);
glVertex2f(0.5,0.5);
glVertex2f(-0.5,0.5);
glVertex2f(-0.5, -0.5);
glVertex2f(0.5, -0.5);
glEnd();
glFlush();
}
I want to translate only the triangle, not the square.How to do that?
Upvotes: 1
Views: 697
Reputation: 2292
Before you translate, call:
glPushMatrix()
Then after drawing the first polygon, call:
glPopMatrix()
I've also noted you have no glEnd()
call after your first polygon. Additionally, unless there is more code that's not listed, I notice that you don't switch from the modelview to the projection matrix when calling glOrtho()
. This isn't strictly necessary if you are only using the modelview matrix for this example, but the traditional approach is to set up your projection like this:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1, 1, -1, 1, -1, 1);
Then, your render function sets up the modelview matrix for polygon rendering. Again, not a requirement and your example looks like it will do what you need since you are only using one matrix.
Reference: glPushMatrix() OpenGL Documentation
Upvotes: 7