Search code examples
ioscocos2d-iphonegame-physicsgame-loop

Update loop and buttons in cocos2d


I have a simple lunar lander game. I compute positions and everything by integration - e.g. each turn I take vectors and combine them and then apply resulting vector to my lander.

Here comes the question, I have a button that I want to use for thrust. How do I check if it is on during update method? I guess i will have some BOOL flag that gets set to YES when the button is pressed, but when do i set it to NO? Some practical implementation would be great. I use cocos2d-iphone and iOS.


Solution

  • Well, the pseudo code goes as follows:

    1. We shall not use Buttons (aka CCMenuItem), since they provide callbacks only on touch up events. We want touch down, touch exit/entered, touch ended.

    2. In your CCScene that you are displaying, either add a new child that is a subclass of CCLayer or even use one of the CCLayers already present in the CCScene.

    3. In the init of your CClayer subclass, set isTouchEnabled to YES.

    4. Implement the usual methods:
        - (void)ccTouchesBegan:...
        - (void)ccTouchesMoved:...
        - (void)ccTouchesEnded:...
        - (void)ccTouchesCancelled:...
    

    Finally, do your magic in these methods.

    • Get the touch location
    • Check using CGRectContainsPoint whether the touch is within the thrust area.
    • and so on, and so forth...