Split Screen in Cocos2d-x



You only need a few lines of code to Split Screen in Cocos2d-x.


If you are a Cocos2d-x (or vanilla Cocos2d) user, it’s sorry to say that there isn’t a built-in function which allow you to split your screen into 2 different views without messing around with low level OpenGL code.

Example of multiplayer split screen in Super Mario Kart (1992)

However, the good news is you only need a few lines of code to achieve this!

In your cocos2d::CCLayer inherited class, add in this

virtual void visit();

into your header file, because we are going to override the existing visit() function.

What we need to do is actually cut away part of the CCLayer so that it will not render. Then we create another CCLayer for player 2 and add both layers to the scene.

The OpenGL function which does the magic is called glScissor(). All you need is to enable GL_SCISSOR_TEST before you render all the children of that particular CCLayer. Let’s say your CCLayer inherited class is called HelloWorld, the code would looks like this:

void HelloWorld::visit()
{ glEnable(GL_SCISSOR_TEST);
glScissor(0, 0, screenSize.width, screenSize.height / 2);
glDisable(GL_SCISSOR_TEST); }

I will explain a bit what is actually happening. visit() function is actually where all the rendering happens. You don’t need to know how it renders, all you need to do is first, enable GL_SCISSOR_TEST with the function glEnable().

Only after that you are allowed to use the handy little function called glScissor(). The 4 variables which you need to provide for glScissor() are (from left to right):

Position X
Position Y
Then, you need to call all the rendering functions but you don’t have to do it manually (unless you know what you are doing)[]() Just call CCNode::visit() and that’s it! CCNode::visit() has all the rendering functions encapsulated in it so we don’t need to worry anything. It will do the magic for us. after that don’t forget to disable GL_SCISSOR_TEST when you’re done.

So now you will see your layer is cropped. But wait! How about adding the other half of the screen? That’s easy! All you need to do is adding another CCLayer, position it on top of your first layer and add both layers to the scene! Example:

CCScene* HelloWorld::scene()
{ CCScene *scene = CCScene::node();

HelloWorld* layer1 = new HelloWorld();

HelloWorld* layer2 = new HelloWorld();
layer2->setPosition(ccp(0, screenSize.height / 2, screenSize.width, screenSize.height));

return scene; }

Simple and straight forward. That’s all for today!

Waa Cha!

SSIC.jpg (105.9 kB) shawn, 2013-04-10 03:04


Sign up for our newsletter to keep up with the latest developments, releases and updates for Cocos2d-x.