【发布时间】:2011-12-05 19:58:38
【问题描述】:
我想在我的六边形精灵周围创建触摸区域 (CGMutablePathRefs)。我的目标是创建名称为 hexTouchArea1、hexTouchArea2 等的键,因此我开始将它们存储在 NSMutableDictionary 中。但我不能在其中存储 CGMutablePathRefs。我将如何解决问题?
for (int i = 0; i < hexCount; i++) {
hexTouchAreas = [[NSMutableDictionary alloc] init];
CGPoint touchAreaOrigin = ccp(location.x -22, location.y-40);
NSString *touchAreaKey = [NSString stringWithFormat:@"hexTouchArea%d",i];
CGMutablePathRef hexTouchArea = CGPathCreateMutable();
hexTouchArea = [self drawHexagonTouchArea:touchAreaOrigin];
[hexTouchAreas setObject:hexTouchArea forKey:touchAreaKey];
NSLog(@"the touchareas are %@", hexTouchAreas);
}
drawHexagonTouchArea 返回一个 CGMutablePathRef :
-(CGMutablePathRef) drawHexagonTouchArea:(CGPoint)origin
{
CGMutablePathRef path = CGPathCreateMutable();
CGPoint newloc = CGPointMake(origin.x, origin.y);
CGPathMoveToPoint(path, NULL, newloc.x, newloc.y);
CGPathAddLineToPoint(path, NULL, newloc.x -22,newloc.y + 38);
CGPathAddLineToPoint(path, NULL, newloc.x + 0, newloc.y + 76);
CGPathAddLineToPoint(path, NULL, newloc.x + 46, newloc.y + 76);
CGPathAddLineToPoint(path, NULL, newloc.x +66,newloc.y + 40);
CGPathAddLineToPoint(path, NULL, newloc.x +44, newloc.y + 0);
CGPathCloseSubpath(path);
return path;
}
AND : 如何将这些触摸区域分配给 CCSprites,这样如果精灵旋转,它们就不会单独移动?
【问题讨论】:
-
首先,您应该知道您在上面的代码中泄漏了两个 CGMutablePathRefs。如果您使用
CGPathCreateMutable(),则需要将其与CGPathRelease()匹配,否则路径将永远不会被释放。此外,无需在循环内的hexTouchArea初始化中创建路径,因为您只需用-drawHexagonTouchArea:的结果覆盖它。 -
虽然链接的问题处理的是 NSMutableArray 而不是 NSMutableDictionary,但这里也适用相同的原则。
标签: iphone objective-c cocos2d-iphone