OpenGL and Pixels

Started by
2 comments, last by Funkapotamus 18 years, 7 months ago
Ok i am drawinf a total blank here. lets say i want to draw a cube the is 20 X 20 pixels, How would i do that so I use the number 20? is there a way? right now i am doing something like this:

	glBegin( GL_QUADS );
	glColor3f( 1.0f, 1.0f, 1.0f );
		glVertex3f( 0.2f, 0.2f, 0.0f );
		glVertex3f( 0.2f, -0.2f, 0.0f );
		glVertex3f( -0.2f, -0.2f, 0.0f );
		glVertex3f( -0.2f, 0.2f, 0.0f );
	glEnd();

but i want to do something like this:

	glBegin( GL_QUADS );
	glColor3f( 1.0f, 1.0f, 1.0f );
		glVertex3f( 10f, 10f, 0.0f );
		glVertex3f( 10f, -10f, 0.0f );
		glVertex3f( -10f, -10f, 0.0f );
		glVertex3f( -10f, 10f, 0.0f );
	glEnd();

so i start in center and go 10 pixel up and over, and so on. is there a way to do this?
Advertisement
yes, but only if you limit your viewport to always be the same width/height in pixels. Why work in pixels? Work in abstract opengl units unless you have a compelling reason not to.
[size="1"]
Assuming you're trying to do 2D sprite rendering (which is probably be the only compelling reason mrbastard referred to), you can just setup an orthogonal projection that maps your OpenGL coordinates to pixel coordinates. Just provide the viewport size (in pixels) to the glOrtho function.

Tom
Two ways. One is ortho mode described by mrbastard. The other is this:

int width = 1024;int height = 768;glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearDepth(1.0f); glHint(GL11.GL_PERSPECTIVE_CORRECTION_HINT, GL11.GL_NICEST);glViewport(0, 0, width, height );				glMatrixMode(GL11.GL_PROJECTION); glLoadIdentity(); glFrustum(   - width / 64.0,   width  / 64.0,   - height / 64.0,   height  / 64.0,   8,   65536); glMatrixMode(GL11.GL_MODELVIEW);


To draw a 10px quad at the center of the screen you do this:

glTranslatef(0.0f, 0.0f, -256.0f);  // NOTE THE -256!glBegin( GL_QUADS );   glColor3f( 1.0f, 1.0f, 1.0f );   glVertex3f( 10f, 10f, 0.0f );   glVertex3f( 10f, -10f, 0.0f );   glVertex3f( -10f, -10f, 0.0f );   glVertex3f( -10f, 10f, 0.0f );glEnd();

Take note of the -256 z value! At this depth, the lower left corner of the screen is (-width / 2, -height / 2). The upper right corner is (width / 2, height / 2). For my 2d game, I wrote a GL Utility program to automatically translate to the correct place:

private static final float OFFSET_X = width / -2.0f;private static final float OFFSET_Y = height / -2.0f;private static final float OFFSET_Z = -256.0f;public static void funkTranslate(Vector2df location){   glTranslatef(OFFSET_X + location.x, OFFSET_Y + location.y, OFFSET_Z);}

This topic is closed to new replies.

Advertisement