Using Gesture Recognizers In Cocos2d
cocos2d is one of the best gaming framework I’ve seen, but it doesn’t use UIKit. When Apple introduced UIGestureRecognizers they unified how touch interaction should work. You could manually attach gesture recognizers to cocos2d window but then you have to do everything manually. Let me show you easier way…
Some time ago I’ve seen xemus shared his implementation which is pretty cool, but for me it had a a few things that I do not like:
- It requires manual modifying cocos2d, and I prefer not to change libraries I’m using so that I can upgrade anytime to newer versions.
- It uses some wrapper class that I had to be aware of when using gestures, instead of using standard UIGestureRecognizers.
Since I use gesture recognizers in all my cocos2d apps, I’ve rolled my own implementation based on xemus code but I used more dynamic approach.
This is how you add gesture recognizers support for any cocos2d project:
- Download my category CCNode%2BSFGestureRecognizers
- import “CCNode%2BSFGestureRecognizers.h” preferably in your project Prefix.pch
- Make sure you are using llvm compiler. By now you should only be using LLVM.
- Now any node can use gesture recognizers, use standard UIGestureRecognizers, there is no need for special treatment when working with cocos2d.
What you get extra:
- Each UIGestureRecognizer that is assigned to node have now node property so that you can easily use it in your handling code.
- Each node has now isTouchEnabled (doesn’tbreak CCLayer which already had this property), touchRect properties that you can use to define touchable region in your local space.
- If a scene stops running gestures will stop firing as it should ![:)] .
- The code works with both 2.0 and 1.1 cocos2d versions.
I’m merowing_ on twitter if you feel like talking about it.