您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 打磚塊遊戲實作(五):遊戲場景類 GameScene

編輯:iOS 開發綜合

建立遊戲場景類的標頭檔

在 Xcode 中新增一個 GameScene 類,讓它繼承自 CCNode,並將標頭檔替換成以下內容:

 #import CCNode.h @class Stick; @interface GameScene : CCNode  //讀取GameScene中Level中的反彈棒實例 @property (atomic,strong) Stick *stickInGameScene; // @property (nonatomic,assign) BOOL isStickShooting; //返回GameScene當前實例 +(instancetype)sharedGameScene; -(CCPhysicsNode*)physicsWorld; -(void)addBall:(CCSprite*)ball; -(NSInteger)currentBallsCount; @end

這裡加入了一些屬性與方法,主要用來取得與設定遊戲場景中的必要物件,例如小球、反彈棒等等。由於場景裡需要處理物理碰撞,因此我們還額外採用了物理碰撞的委派協議,這一點後續會用到。

實作遊戲場景類

在 GameScene.m 中實作初始化邏輯:

 -(void)didLoadFromCCB{ //初始化內部靜態變量 sharedGameScene = self; //加載當前Level節點 GameState *gameState = [GameState sharedInstance]; _level = (Level*)[CCBReader load:gameState.currentLevel]; [self addChild:_level]; _level.zOrder = 50; //初始化GameScene中反彈棒實例變量 self.stickInGameScene = (Stick*)[self getChildByName:@stick recursively:YES]; NSAssert(self.stickInGameScene, @stickInGameScene must not nil); //初始化得分比率 _scoreRatio = 1; //取得Level中的物理世界對象 _physicsWorld = (CCPhysicsNode*)[self getChildByName:@physicsWorld recursively:YES]; NSAssert(_physicsWorld, @physicsWorld must not nil); //打開物理調試顯示 _physicsWorld.debugDraw = YES; //設置物理碰撞代理 _physicsWorld.collisionDelegate = self; _userInterface.zOrder = 100; _msgLabel.zOrder = 101; self.userInteractionEnabled = YES; self.zOrder = 0; _balls = [NSMutableArray array]; _viewSize = [CCDirector sharedDirector].viewSize; }

這段程式碼大致完成了以下幾件事:

建立自身的共享單例、載入當前的 Level 場景(Level 場景會在後續文章中介紹)、初始化反彈棒與物理世界,並設定各個場景節點的 Z 序。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved