JustinWong

做纯粹的快乐的游戏

导航

cocos2d利用反射做扩展型物品的代码组织

Posted on 2011-06-13 21:51  JustinWong  阅读(394)  评论(1)    收藏  举报

比如在主layer中的初始化时读到一个misc的dic。

循环取出每一个misc物品,初始化并加入该layer:

for (NSDictionary *fv_dicMisc in lv_arrayMisc) {
MiscBase
*fv_misc = [MiscBase miscWithTheme:themeName_
andTypeName:[fv_dicMisc objectForKey:
@"type"]
andStyle:[[fv_dicMisc objectForKey:
@"styleId"] intValue]
andPosition:ccp([[fv_dicMisc objectForKey:
@"x"] intValue], [[fv_dicMisc objectForKey:@"y"] intValue])
];
[self addChild:fv_misc z:
-5];
}

其中MiscBase作为这种物品的基类,interface如下:

@interface MiscBase : CCSprite {
NSString
*mv_strTheme;
NSString
*mv_strType;
int mv_iStyle;
CGPoint mv_position;
}

+ (id)miscWithTheme:(NSString *)theme andTypeName:(NSString *)type andStyle:(int)styleId andPosition:(CGPoint)pos;

@end

接下来在实现的部分,利用反射alloc具体类型,并且调用MiscBase的初始化来初始化公共属性:

@implementation MiscBase

- (void) initByChild {

}

- (id)initWithTheme:(NSString *)theme andTypeName:(NSString *)type andStyle:(int)styleId andPosition:(CGPoint)pos {
if ((self = [super init])) {
mv_strTheme
= [theme retain];
mv_strType
= [type retain];
mv_iStyle
= styleId;
mv_position
= pos;
[self initByChild];
}
return self;
}

+ (id)miscWithTheme:(NSString *)theme andTypeName:(NSString *)type andStyle:(int)styleId andPosition:(CGPoint)pos {
return [[[NSClassFromString(type) alloc] initWithTheme:theme andTypeName:type andStyle:styleId andPosition:pos] autorelease];
}

- (void)dealloc {
[mv_strTheme release];
[mv_strType release];
[super dealloc];
}

@end

子类就可以随意来实现了,比如一个星空的效果:

@implementation SkyStar

- (void)initByChild {
// 具体实现
}

- (void)dealloc {
[super dealloc];
}

@end

之后如果增加了新的杂项,只需要创建新类继承MiscBase,并实现即可。这种方式可以很好的处理不同游戏场景中的一些独特的小物体和小零件,增加趣味性。