我正在尝试使用ccDrawPoly创建一些随机看起来像小行星的多边形。为此,我编写了一个简单的函数,它在一个段中绘制一个圆(在每次迭代中随机化圆半径)以创建一种“凹凸不平”的多边形。顶点存储在NSMutableArray中,然后输入ccDrawPolygon(下面的代码):
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在调用draw的内部崩溃。我相信我的问题可能在于如何从我的NSMutableArray缓存中抓取多边形顶点并尝试绘制它们:
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);
有关更多信息,我在cocos2d崩溃之前已经包含了顶点数组内容的示例。为了使其更容易可视化,我已经包含了我创建的图形(蓝色像素表示圆心,白色像素是顶点,红色线是连接它们的线)。
(
(
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"
)
)
答案 0 :(得分:1)
你是否在绘制方法之外绘图?如果您愿意,以下说明可能有所帮助。
您不能在CCNode绘制功能之外使用ccDrawPoly。 注意它以大写字母 表示'不要在此方法之外绘制你的东西' 。在以下CCNode绘制方法的定义中。
// This is CCNode's draw method
-(void) draw
{
// override me
// Only use this function to draw your stuff.
// DON'T draw your stuff outside this method
}
cocos2d-ios中的ccDrawPoly示例:ActionsTest.m
-(void) draw
{
CGSize winSize = [[CCDirector sharedDirector] winSize];
float x = winSize.width*2 - 100;
float y = winSize.height;
CGPoint vertices[] = { ccp(5,5), ccp(x-5,5), ccp(x-5,y-5), ccp(5,y-5) };
ccDrawPoly(vertices, 4, YES);
}