Drawing a dashed line in cocos2d

A code snippet for drawing a dashed line in cocos2d. Could also be modified to draw in other engines such as OpenGL by removing cocos2d convenience methods.

void drawDashedLine(CGPoint origin, CGPoint destination, float dashLength)
{
CGPoint delta = ccpSub(destination, origin);
float dist = ccpDistance(origin, destination);
float x = delta.x / dist * dashLength;
float y = delta.y / dist * dashLength;
float linePercentage = 0.5f;

CGPoint p1 = origin;
for(float i = 0; i <= dist / dashLength * linePercentage; i++)
{
CGPoint p2 = CGPointMake(p1.x + x, p1.y + y);
ccDrawLine(p1, p2);
p1 = CGPointMake(p1.x + x / linePercentage, p1.y + y / linePercentage);
}
}

The code works by drawing lots of small lines. This can be quite bad for performance if used in the draw method. A better way is to draw into a CCRenderTexture which reduces the number of draw calls significantly, of course if you need to update the line this may not help.

You can change the percentage of line drawn versus spacing by modifying the linePercentage variable. The algorithm splits the dashLength into line and space based on this percentage. Experiment to see what you like best.