Drawing with openGL on Cocos2d-iphone


/ Published in: iPhone
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /*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.
  2. I'm using the version 0.99.1 of cocos2d-iphone.
  3. 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.
  4. To save some time to the ones that were having the same problem here goes my solution.
  5. I created a very simple class that draws colored line.
  6. The class declaration is minimal:
  7. */
  8.  
  9. @interface Line : CCNode
  10. {
  11. }
  12.  
  13. @end
  14.  
  15. /*
  16. It just has to subclass the CCNode class from cocos2d-iphone.
  17. For the implementation I just had to overload the draw() method.
  18. */
  19.  
  20. @implementation Line
  21.  
  22. -(void) draw
  23. {
  24. static const GLfloat vertices[] =
  25. {
  26. 0.0, 0.0,
  27. 250.0, 280.0
  28. };
  29. static const GLubyte squareColors[] = {
  30. 255, 0, 0, 255,
  31. 0, 0, 255, 255
  32. };
  33.  
  34. glDisable(GL_TEXTURE_2D);
  35. BOOL colorArrayEnabled = glIsEnabled(GL_COLOR_ARRAY);
  36. if (!colorArrayEnabled) {
  37. glEnableClientState(GL_COLOR_ARRAY);
  38. }
  39.  
  40. BOOL vertexArrayEnabled = glIsEnabled(GL_VERTEX_ARRAY);
  41. if (!vertexArrayEnabled) {
  42. glEnableClientState(GL_VERTEX_ARRAY);
  43. }
  44.  
  45. glLineWidth(2.0f);
  46. glColorPointer(4, GL_UNSIGNED_BYTE, 0, squareColors);
  47. glVertexPointer(2, GL_FLOAT, 0, vertices);
  48. glDrawArrays(GL_LINES, 0, 2);
  49.  
  50. if (!vertexArrayEnabled) {
  51. glDisableClientState(GL_VERTEX_ARRAY);
  52. }
  53.  
  54. if (!colorArrayEnabled) {
  55. glDisableClientState(GL_COLOR_ARRAY);
  56. }
  57. glEnable(GL_TEXTURE_2D);
  58. }
  59.  
  60. @end
  61. /*
  62. 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.
  63. I found out in a forum that having GL_TEXTURE_2D enabled won't allow you to make any drawing with openGL primitives.
  64. Then I was using just vertex arrays with a call to glColor4f(), but this result in a line with no color.
  65.  
  66. 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.
  67. I hope this will save you some hours of work.*/

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.