0

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

2
  • The code you posted doesn't compile. Commented Jun 25, 2012 at 16:14
  • How can we work with an example that doesn't work. Commented Jun 25, 2012 at 16:36

2 Answers 2

1

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/

Sign up to request clarification or add additional context in comments.

5 Comments

hello sentinel,, my button works fine...but the sprite keeps on moving when button is tapped .It is not stopping even after release,i want to stop when button is released
to do this, you need to catch button release moment. to do this, you need subclass button.
I cannot understand that example sentinel...can i get another example
as @SentineL sais, subclass the type of button you want. Also override the 'unselected' method. Your class will be served a callback to that method when the button becomes unselected for any reason (finger off, finger slides off label, finger slides off screen). In that method, set the sprite velocity to 0.
Sorry, I have no more examples. In my project I used that one. Hope, YvesLeBrog's post makes it more clear.
0

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?

3 Comments

Yea i tried it but it works when i touch somewhere else on screen , but not when i press and release CCMenu button.
check CCMenuItemFont *item1 = [CCMenuItemFont itemFromString: @"icon.png" target:self selector:@selector(doit)]; ,,
I oversaw that, sorry... I think that @SentineL gave you the right answer... you need to override the standard behavior of cocos2d buttons to handle the "touchUp" event...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.