vishnu
vishnu

Reputation: 879

Cocos2d-iphone : Handle Button Press and Release

Actually I need to move my sprite as long as button is pressed and the sprite should be stopped when button is released.

My code is below:

 CCMenuItemFont *item1 = [CCMenuItemFont itemFromString: @"icon.png" target:self selector:@selector(doit)];
        CCMenu * taskMenu = [CCMenu menuWithItems:item1,  nil];
        [self addChild:taskMenu];

-void()doit
{
        spritevelocity = 80;
}

The above code makes my sprite keep on moving when the button is tapped, but I need to stop my sprite as soon as button is released.

I tried below code but no success:

-void()doit
{
    buttonpressed = YES;
    if (buttonpressed) {
        spritevelocity = 80;
    }
}

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
         buttonpressed = NO;
}

Note:I just wanted to make spritevelocity = 0 to stop my sprite,,That is i want spritevelocity = 0 when button is released

Upvotes: 0

Views: 2958

Answers (2)

sergio
sergio

Reputation: 69027

Why don't you set the velocity directly?

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
     buttonpressed = NO;
     spritevelocity = 0;
 }

Could you explain when is doIt called?

Upvotes: 0

SentineL
SentineL

Reputation: 4732

You need to subclass CCMenuItem in case to override selected, unselected and activate methods. there, you can force you button to act as you whant to. In this case, act not only on press, but on release too. Here is a good example of overriding CCMenu: http://johnehartzog.com/2009/10/easy-to-create-buttons-with-cocos2d/

Upvotes: 1

Related Questions