Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D Drawing In OpenGL ES 2.0 (iOS)

I'm learning how to use OpenGL ES 2.0 on iOS. Right now I want to just do some basic 2D animation (e.g. move a rectangle around the screen and change its size). I've started out with the project template for OpenGL ES provided by Apple in Xcode. My drawing code looks like this:

static GLfloat squareVertices[] = {
    -0.5f, -0.33f,
    0.5f, -0.33f,
    -0.5f,  0.33f,
    0.5f,  0.33f
 };

// Update attribute values.
glVertexAttribPointer(VERTEX_ATTR, 2, GL_FLOAT, 0, 0, squareVertices);
glEnableVertexAttribArray(VERTEX_ATTR);

glVertexAttribPointer(COLOR_ATTR, 4, GL_UNSIGNED_BYTE, 1, 0, squareColors);
glEnableVertexAttribArray(COLOR_ATTR);

glDrawArrays(GL_TRIANGLE_STRIP, 0, 5);

Now this will draw a nice rectangle in the middle of the screen. But if I start to change the rectangle by adding the following code, it starts to look funky:

squareVertices[5] -= .001;
squareVertices[7] -= .001;

It is as if part of the rectangle is attached to the center of the screen. I am completely new to OpenGL ES so I'm sure my problem is obvious. I also assume this has something to do with OpenGL ES being a 3D graphics library and I'm trying to treat it as a 2D space. So my question is: What is the best way to draw and animate 2D objects in OpenGL ES 2.0? I've seen some stuff online for OpenGL ES 1.1, but that is not much help to me. Are their special techniques for 2D drawing in OpenGL ES 2.0, or is there some sort of 2D drawing mode?

Any guidance would be greatly appreciated.

like image 531
joshwbrick Avatar asked Dec 04 '25 09:12

joshwbrick


1 Answers

@macinjosh: This is a response to your updated question for those who are interested in the answer. I'm guessing you've gained further knowledge since Dec '10 when you posted!

OpenGL vertices are in 3D, not 2D. To be completely truthful, they're actually in 4D since they include a 'w' component as well, but for now just consider that as value 1.0 like a homogenous vector.

Due to their 3D-ness, unless you add a 'z' component in a shader you must specify one as a vertex attribute.

like image 136
KomodoDave Avatar answered Dec 05 '25 22:12

KomodoDave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!