Friday, April 17, 2009

Drawing a Textured Line in OpenGL ES

Currently I'm still playing around with the CrashLanding demo app as my sandbox :) Those red spotted lines are my textured lines.

I wanted to draw a textured line and opengl doesn't support drawing textured lines as such. You need to create a polygon (actually two triangles), and texture them.

So I created a simple class which takes two points, calculates the length and angle with the horizontal line. Then I calculate the vertex coordinates and the texture coordinates.

These coordinates are generated as if I am creating a horizontal line. And then before drawing I simply rotate the model view matrix. The vertex coordinates would be something like this
0, -w/2
0, w/2
length, w/2
length, -w/2
where length is the length of the line and w is the width of the line

The texture coordinates would be calculated as follows:
0, 0
0, 1
length / tw, 1
length / tw, 0
where tw is the texture width.

Then draw the two triangles to create the textured line.

glBindTexture(GL_TEXTURE_2D, [_texture name]);
glTranslatef(_point.x, _point.y, 0);
glRotatef(_angle, 0, 0, 1);

glVertexPointer(2, GL_FLOAT, 0, _vertexArray);
glTexCoordPointer(2, GL_FLOAT, 0, _textCoordArray);

glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

No comments: