Cocos2d-iphone:按键按下并释放

时间:2012-06-25 16:12:52

标签: iphone ios cocos2d-iphone

实际上,只要按下按钮,我就需要移动我的精灵,释放按钮时应该停止精灵。

我的代码如下:

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

-void()doit
{
        spritevelocity = 80;
}

上面的代码使我的精灵在按下按钮时继续移动,但是我需要在按钮释放后立即停止我的精灵。

我尝试了以下代码,但没有成功:

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

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

注意:我只是想让spritevelocity = 0来停止我的精灵,那就是当按钮被释放时我想要spritevelocity = 0

2 个答案:

答案 0 :(得分:1)

您需要子类化CCMenuItem,以便覆盖selectedunselectedactivate方法。在那里,你可以强迫你按钮按照你的意愿行事。在这种情况下,不仅要按压,还要放行。以下是覆盖CCMenu的一个很好的示例:http://johnehartzog.com/2009/10/easy-to-create-buttons-with-cocos2d/

答案 1 :(得分:0)

为什么不直接设置速度?

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

你能解释一下doIt何时被召唤?