Wednesday, December 3, 2008

cocos2d: Parallax scrolling


cocos2d v0.6 introduces Parallax Scrolling. For those who don't know the meaning of Parallax Scrolling, it is a way to simulate a 3D environment scrolling layers in a 2D environment.

(When I think of Parallax Scroller I think of Shadow of the Beast.)

As you can see from the screenshot, the image is composed of a Parallax Scrolling of 3 layers:
  • A) A 'powered by cocos2d' image
  • B) A tilemap
  • C) A background image
When you move the image, the layers start to scroll at different speeds simulating a 3D environment.

How do you code a parallax scrolling in cocos2d ?
// You need a parent node
// It can be an empty node, or a node with images. Your choice
CocosNode *voidNode = [CocosNode node];


// Then you add the children, using the 'add' selector.
// But with the additional parallaxRatio

// example:
// a child that will move at 0.4 ratio horizontally
// and 0.5 ratio vertically
[voidNode add:background z:-1 parallaxRatio:cpv(0.4,0.5)];

// another child with a ratio of 2.2x, 1.0y
[voidNode add:tilemap z:1 parallaxRatio:cpv(2.2,1.0)];

// and another child (top one) that is moved at a ratio of 3.0x, 2.5y
[voidNode add:cocosImage z:2 parallaxRatio:cpv(3.0,2.5)];

That's all.

If you want to alter the Parallax Ratio, you can modify the parallaxRatio property. Eg:
background.parallaxRatio = cpv(1.5, 0.5);
tilemap.parallaxRatioX = 2;
tilemap.parallaxRatioY = 0.9;

Working Example: ParallaxDemo example. See TestParallax.m file.

5 comments:

Anonymous said...

Hey, can i check out the "unstable" 0.6 version from the SVN?

Thanks,
Boris

PJ Cabrera said...

Hi Riq,

When is Cocos-iphone 0.6 going to be available for download? The improvements you are making sound great and I can't wait to check them out.

riq said...

boris: sure, you can check it out from the svn. check out 'trunk'.

PJ Cabrera: tomorrow friday I will release version 0.6.0.

TJ Holowaychuk said...

I am not sure if I am missing something but should cpv(0,0) or cpv(1,1) make it still? For example i have the following three layers:

http://gist.github.com/96706

where the 'background' should hardly move, 'midground2' should move a bit, and 'midground' should be the playable layer that does not move. The values I have set work, the numbers just seem strange its hard to figure out without re-building the project

riq said...

Hi Test,

Could you post it in the cocos2d forum ? Perhaps someone had the same issue and he knows how to solve it.

http://groups.google.com/group/cocos2d-iphone-discuss

Also, if it is a bug, could you open an issue here:
http://code.google.com/p/cocos2d-iphone/issues/list

thanks