Created
September 27, 2014 16:59
-
-
Save LearnCocos2D/69891adcc110082b25a8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-(void) draw:(CCRenderer *)renderer transform:(const GLKMatrix4 *)transform | |
{ | |
// Drawing the triangle fan. Simple explanation of how a triangle fan is drawn: | |
// http://stackoverflow.com/questions/8043923/gl-triangle-fan-explanation | |
// in a triangle fan the first 3 vertices form one triangle, then each additional vertex forms another triangle | |
// thus number of triangles is number of vertices minus the initial 2 vertices for the first triangle | |
int numTriangles = _numVertices - 2; | |
CCRenderBuffer buffer = [renderer enqueueTriangles:numTriangles | |
andVertexes:_numVertices | |
withState:self.renderState | |
globalSortOrder:0]; | |
// update the vertex coordinates using each child node's current position, and add them to the render buffer | |
int i = 0; | |
CGPoint centerPos = ((CCNode*)_children[0]).position; | |
for (CCNode* child in _children) | |
{ | |
CGPoint vertexPos = child.position; | |
if (i > 0) | |
{ | |
// elongate vertex position outwards by the body size | |
CGPoint vectorToCenter = ccpSub(child.position, centerPos); | |
CGFloat length = ccpLength(vectorToCenter); | |
CGPoint normalVector = ccpMult(vectorToCenter, 1.0 / length); | |
vectorToCenter = ccpMult(normalVector, length + _enlargeDrawRadius); | |
vertexPos = ccpAdd(vectorToCenter, centerPos); | |
} | |
_vertices[i].position = GLKVector4Make(vertexPos.x, vertexPos.y, 0.0, 1.0); | |
CCRenderBufferSetVertex(buffer, i, CCVertexApplyTransform(_vertices[i], transform)); | |
i++; | |
} | |
// adding the first circumference vertex as the last vertex closes the (circular) polygon | |
int lastIndex = _numVertices - 1; | |
_vertices[lastIndex].position = GLKVector4Make(_vertices[1].position.x, _vertices[1].position.y, 0.0, 1.0); | |
CCRenderBufferSetVertex(buffer, lastIndex, CCVertexApplyTransform(_vertices[lastIndex], transform)); | |
for (int i = 0; i < numTriangles; i++) | |
{ | |
// draw triangle from center (0) to circumference vertices (i+1, i+2), re-using each circumference vertex twice | |
CCRenderBufferSetTriangle(buffer, i, 0, i+1, i+2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
above code draws a sprite by using the physicsbody child nodes as initial vertices and texture coordinates
(ie draws a soft-body physics sprite)