根據上次的練習 [Cocos2D-x] 第一個練習範例 : Moving Background。

Screen Shot 2013-03-02 at 上午10.56.39

我們已經學會了如何做無限移動的前景和背景,後來 Alan 發現利用 Cocos2D 提供的一個 Class:CCParallaxNode 也可以辦到,雖然無法直接滿足 100% 的需求,需要透過一些自己撰寫的方法,但這個 class 在很多時候可能可以省去開發者許多的時間,先讓我們來看看 class 的定義: 

CCParallaxNode: A node that simulates a parallax scroller

The children will be moved faster / slower than the parent according the the parallax ratio.

意思是,加入這個  CCParallaxNode *parent 類別的 children 物件會和 parent 一起做移動,移動的速度會參考一個 ratio 相對於 paraent,依據 ratio 設定的不同即可模擬出許多 parallax 的效果 (動比較慢的感覺是遠景,動比較快的是近景)。

CCParallaxNode 包含了一個 property 和一個 method :

// array that holds the offset / ratio of the children : 假如在 children 加入 CCParallaxNode 後想要再度存取 children 屬性就必須透過這個 array

@property (nonatomic, readwrite) ccArray *parallaxArray

// Adds a child to the container with a z-order, a parallax ratio and a position offset It returns self, so you can chain several addChilds:主要會用到的 method

- (void)addChild:(CCNode *)node z:(NSInteger)z parallaxRatio:(CGPoint)c positionOffset:(CGPoint)positionOffset

- node : 欲加入的節點

- z : 深度(圖層的前後)

- parallaxRatio : 透過 CGPoint 來設定的相對 (x,y) 速度,經測試假如設為 (0.5,0) 那 parent 移動 x=1 則 children 移動 x=0.5

- PositionOffset : children 在 parent 中的起始位置

程式該怎麼寫?

0. 將 CCParallaxNode-Extras.h import,此為網路上一個開發者提供的一個 CCParallaxNode category,讓我們可以存取並修改 ParallaxNode 中的 children node (下載位置

1. 先宣告要用到的物件,因為再 init 之後在 update 中還會用到,所以宣告為全域變數:

Screen Shot 2013-03-08 at 下午12.06.11  

2. 將以下程式碼加入到 HellorWorldLayer 中的 init :

Screen Shot 2013-03-08 at 下午12.03.02  

3. 撰寫 update method,在 update 中我們要判斷 CCParallaxNode 中的 child position 是否小於某個值 (在本範例中為 background.contentSize.width),是的話就加一個 offset (background.contentSize.width * 2) 將它移動到需要的位置:

Screen Shot 2013-03-08 at 下午12.14.33  

註:update中的 -(void) incrementOffset:(CGPoint)offset forChild:(CCNode*)node; 為 CCParallaxNode-Extras 中定義的 method,協助我們找出 ParallaxNode中的子節點並將子節點的位置加上一個 offset。

 

後記:在此範例中使用 CCParallaxNode 好像沒有比自己動手計算坐標跟移動方便很多,但假如未來製作的遊戲中有很多的物件需要做相對的移動那此類別應該會讓需求更容易更快被實現。  

 

----------參考資料----------

http://www.raywenderlich.com/3611/how-to-make-a-space-shooter-iphone-game

http://www.cnblogs.com/iosfans/archive/2011/12/18/2292734.html

-----------範例下載-------------

https://docs.google.com/file/d/0B-qc8N2DnfJddWtQZlQySUNNaXM/edit?usp=sharing

----------------------------------

Thinking.jpg  

筆者:Alan Feng

大學由資管系畢業後便投入職場,先後擔任程式設計師,系統設計師,系統分析師,專案管理師等職務。

曾服務於資訊服務業,電子代工設計公司,目前在內湖一間遊戲公司擔任專案管理師~

持有國際 PMP 證照並努力學習 Scrum 敏捷式開發框架中。


arrow
arrow

    Alan Feng 發表在 痞客邦 留言(0) 人氣()