根据上次的练习 [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 敏捷式开发框架中。


相关文章