Return to Snippet

Revision: 39761
at January 20, 2011 16:40 by willwish


Initial Code
/*After a long search in the web, forums, IRC chats and several hours of trial and error... I finally can make some openGL drawing inside cocos2d-iphone objects.
I'm using the version 0.99.1 of cocos2d-iphone.
In the beginning the code was breaking in the call to glDrawArrays() with a EXC_BAD_ACCESS exception. Then I was able to draw a line but there was no color.
To save some time to the ones that were having the same problem here goes my solution.
I created a very simple class that draws colored line.
The class declaration is minimal:
*/

@interface Line : CCNode
{
}

@end

/*
It just has to subclass the CCNode class from cocos2d-iphone.
For the implementation I just had to overload the draw() method.
*/

@implementation Line

-(void) draw
{
static const GLfloat vertices[] =
{
0.0, 0.0,
250.0, 280.0
};
static const GLubyte squareColors[] = {
255, 0, 0, 255,
0, 0, 255, 255
};

glDisable(GL_TEXTURE_2D);
BOOL colorArrayEnabled = glIsEnabled(GL_COLOR_ARRAY);
if (!colorArrayEnabled) {
glEnableClientState(GL_COLOR_ARRAY);
}

BOOL vertexArrayEnabled = glIsEnabled(GL_VERTEX_ARRAY);
if (!vertexArrayEnabled) {
glEnableClientState(GL_VERTEX_ARRAY);
}

glLineWidth(2.0f);
glColorPointer(4, GL_UNSIGNED_BYTE, 0, squareColors);
glVertexPointer(2, GL_FLOAT, 0, vertices);
glDrawArrays(GL_LINES, 0, 2);

if (!vertexArrayEnabled) {
glDisableClientState(GL_VERTEX_ARRAY);
}

if (!colorArrayEnabled) {
glDisableClientState(GL_COLOR_ARRAY);
}
glEnable(GL_TEXTURE_2D);
}

@end
/*
The important parts are that you have to disable GL_TEXTURE_2D and you need to use both color and vertex arrays to do the drawing.
I found out in a forum that having GL_TEXTURE_2D enabled won't allow you to make any drawing with openGL primitives.
Then I was using just vertex arrays with a call to glColor4f(), but this result in a line with no color.

This class is very simple to change so that you can specify the star and end point of the line and the color when you initialize the object.
I hope this will save you some hours of work.*/

Initial URL
http://rev2k.blogspot.com/2010/03/drawing-with-opengl-on-cocos2d-iphone.html

Initial Description

                                

Initial Title
Drawing with openGL on Cocos2d-iphone

Initial Tags

                                

Initial Language
iPhone