简体   繁体   中英

How to repeat an action while MenuItem button is held down? (cocos2d)

How to repeat an action while MenuItem button is held down? I tried to make a subclass on CCMenuItemImage and made

@implementation CCMenuItemSpriteHoldable

@synthesize buttonHeld;

-(void) selected
{
[super selected];
buttonHeld = true;
}
-(void) unselected
{
[super unselected];
buttonHeld = false;
}

@end

and put this on my init

CCMenuItem *upButtonItem = [CCMenuItemSpriteHoldable
                            itemFromNormalImage:@"up.png" selectedImage:@"upsel.png"
                            target:self selector:@selector(upButtonTapped:)];

but it did nothing... :( it just loads the (void) upButtonTapped when I release the button. is there any way to make a button that allows u to hold down?

Thank you

You must add a CCSprite in a CCLayer, implement the CCLayer touch (begin, moved, ended) catch when the user tap over your CCSprite (using [yourSprite boundingBox]) and start a selector pressed: when user touch begin over your buttons CCSprite and unschedule selector on touch ended!

NB unschedule the pressed: selector if in touch moved touch exit from your button CCSprite bounding box

I can only answer for Cocos2dX but it should be the same mechanism. It is a bit hacky to implement this feature so I suggest you go the way with subclassing the Sprite and add a CCLayerTouch to it.

But if you want to use CCMenuItem I can tell you where you should start looking. Every time the user is touching a CCMenuItem-(Node) the class checks which children was getting touched and sets this children to selected. When you release you finger, it sets it back to unselected and fires the selector (action) you assigned to it. This is a one time action.

Two ways now:

  1. In order to make it fire all the time, you need to subclass CCMenuItem and override the four touch callbacks (without calling super). In the touchbegan , you register your sprite as being touched and in the touchend you unregister it. You class needs also an update() method which will get called every frame in your runloop. In this update() method you test if the sprite is touched, and if yes you fire. This is a less cocos-style approach.

  2. As mentioned above. Register a scheduler, and and unregister when a touch ends.

The touch moved method is not doing anything in this case. And the touchCancelled methods behaves like the touchEnded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM