Create a D-pad with Cocos2d

Cocos2d is a popular native game framework which is out there for many years. There are several version of Cocos2d like Cocos2d-x or Cocos2d-html5. Cocos2d also supports different coding languages, such as lua, C++ and Javascript. This features makes Cocos2d a really powerful tool when it comes to real cross device solutions, code once and deploy it everywhere immediately.
I assume you already have set up your Cocos2d environment, and you know how to create an empty project. We will start of with the basic project template provided by CocosStudio and use javascript as coding language. After some basic coding we will end up with a customizable D-pad which will work on every platform supported by Cocos2d.



New to cocos2d? Here some helpful links:
 Getting Started


D-pad script

Test the D-pad capabilities in the HTML5 version


Starting off with extending a cc.Laye class, which will handle our touch inputs and draw the sprites. We can easily add all the touch events we need to this layer. Since we have multi touch response, we need to check each touch coordinate with the position of our input elements. Once the positions overlaps the input element will be activated. While a button element has just a pressed state, the analog stick will return an x and y value between -1 and 1.
The analog stick gets updated each time the touch-move event occurs. Once the touch-end event is fired, the input element state will fall back to deactivated.
Once the script is included into your cocos2d project you can add a analog-stick or a button by a simple command. You should definitely customize your input script to perfectly fit into your theme.




how to use

Make sure you have copied or changed the necessarily graphic assets. Simply add a new touch controller layer to the scene. Add buttons and analog sticks as required.
I highly encourage you to check an manipulate the touchController.js script to fit your needs perfectly.



Cocos2d is a great cross device game engine, unfortunately it will take a lot of time to fully understand how cocos2d works and how to use the javascript version of it. Once you feel comfortable with cocos2d you can easily build 2d games for any target device natively and in html5.
Having a D-pad is a good starting point, you have to control the player somehow. Even better, this D-pad will work on Android, iOs, html5 and most desktop operating systems without any customization.