回到 Xcode,我們來建立關卡類別與過關條件設定。首先新建 Level1 類別,繼承自 CCNode。
打開 Level1.m,在初始化方法中加入如下呼叫:
-(void)didLoadFromCCB {
[self initBasket];
[self initRestrict];
}
接著分別實作這兩個方法。
首先是 initBasket,透過 Action 讓籃筐上下移動,並保持動作永遠循環:
-(void)initBasket {
CCActionMoveBy *mov1 = [CCActionMoveBy actionWithDuration:5 position:ccp(0, -0.7)];
CCActionMoveBy *mov2 = [CCActionMoveBy actionWithDuration:5 position:ccp(0, 0.7)];
CCActionSequence *seq = [CCActionSequence actions:mov1, mov2, nil];
CCActionRepeatForever *repeat = [CCActionRepeatForever actionWithAction:seq];
[_basket runAction:repeat];
}
每一關都有特定的過關條件,類別 LevelRestrict 便是用來保存這些條件的類別,其中 bulletCount、timeCount 與 scoreCount 分別代表該關卡的子彈限制、時間限制與分數限制:
-(void)initRestrict {
LevelRestrict *lr = [LevelRestrict sharedInstance];
lr.bulletCount = 10;
lr.timeCount = 60;
lr.scoreCount = 3;
}
在 Xcode 中新建 LevelRestrict 類別,繼承自 NSObject,並以單例模式實作:
@interface LevelRestrict : NSObject
@property (nonatomic, assign) NSInteger bulletCount;
@property (nonatomic, assign) NSInteger timeCount;
@property (nonatomic, assign) NSInteger scoreCount;
@property (nonatomic, strong) NSString *levelName;
+ (instancetype)sharedInstance;
- (void)print;
@end
@implementation LevelRestrict
+ (instancetype)sharedInstance {
static LevelRestrict *sharedLevelRestrict;
if (!sharedLevelRestrict) {
sharedLevelRestrict = [LevelRestrict new];
}
return sharedLevelRestrict;
}
@end
透過這樣的設計,每一關的限制條件都能被集中管理與輕鬆調整,讓關卡邏輯更加清晰。