I’m trying to use ccDrawPoly to create some random looking asteroid-like polygons. To do this, I’ve written a simple function that draws a circle in segments (randomizing the circles radius over each iteration) to create a sort of ‘bumpy’ polygon. The vertices are stored in an NSMutableArray and then fed to ccDrawPolygon (code below):
float maxRadiusVariation = self.radius * 0.2; // 20% of radius
float cx = self.radius, cy = self.radius;
int minSegmentAngle = 5;
int maxSegmentAngle = 45;
int angle = 0;
while(angle < 360)
{
float newRadius = self.radius/2 + rand()%(int)maxRadiusVariation;
float x = cx + (cos(CC_DEGREES_TO_RADIANS(angle)) * newRadius);
float y = cy + (sin(CC_DEGREES_TO_RADIANS(angle)) * newRadius);
[vertices addObject:[NSArray arrayWithObjects:[NSNumber numberWithFloat:x], [NSNumber numberWithFloat:y], nil]];
int angleIncrement = minSegmentAngle + rand()%maxSegmentAngle;
angle += angleIncrement;
}
cocos2d is crashing internally on a call to draw. I believe my problem may be in how I’m grabbing the polygon vertices out of my NSMutableArray cache and attempting to plot them:
CGPoint cgVertices[[vertices count]];
for(int i = 0; i < [vertices count]; i++)
{
NSArray *vertex = [vertices objectAtIndex:i];
float x = [[vertex objectAtIndex:0] floatValue];
float y = [[vertex objectAtIndex:1] floatValue];
cgVertices[i] = ccp(x, y);
}
ccDrawPoly(cgVertices, [vertices count], YES);
For a bit of further information, I’ve included an example of the vertices array contents before cocos2d crashes. To make it a little easier to visualise, I’ve included a graphic I created (where the blue pixel represents the circles centre, the white pixels are vertexes and the red lines are the lines connecting them).
(
(
93,
60
),
(
"96.25231",
"76.90473"
),
(
"91.17692",
78
),
(
"83.78063",
"81.41218"
),
(
"78.77886",
"95.3179"
),
(
"68.77309",
"98.00043"
),
(
44,
"87.71281"
),
(
"34.08406",
"87.79144"
),
(
"26.45318",
"81.78556"
),
(
"22.51079",
"70.74986"
),
(
"23.02254",
"61.29128"
),
(
"27.64341",
"44.21864"
),
(
"30.8436",
"37.22053"
),
(
"52.57661",
"27.84579"
),
(
"62.44148",
"25.08526"
),
(
"73.42231",
"29.853"
),
(
"84.13467",
"37.49406"
),
(
"89.13047",
"49.39737"
)
)
Are you drawing outside the draw method? If you are, the following explanation might help.
You cannot use ccDrawPoly outside the CCNode draw function.
Notice it states in caps ‘DON’T draw your stuff outside this method’. In the following definition of CCNode’s draw method.
// This is CCNode's draw methodExample of ccDrawPoly in cocos2d-ios: ActionsTest.m
Source:Draw and Update Reference