【问题标题】:How add an Action to a Button in cocos2dcocos2d中如何为按钮添加动作
【发布时间】:2013-05-07 08:11:14
【问题描述】:

我使用此代码为我的 cocos2d 项目创建了我的 Button

CCMenuItem *starMenuItem = [CCMenuItemImage 
  itemFromNormalImage:@"ButtonStar.jpg" selectedImage:@"ButtonStarSel.jpg" 
  target:self selector:@selector(starButtonTapped:)];
starMenuItem.position = ccp(60, 60);
CCMenu *starMenu = [CCMenu menuWithItems:starMenuItem, nil];
starMenu.position = CGPointZero;
[self addChild:starMenu];

现在我需要将我的精灵跳跃动作与这个按钮联系起来.. 我该怎么做..?

【问题讨论】:

标签: iphone ios cocos2d-iphone


【解决方案1】:

你可以这样做,

CCLabelBMFont *startLabel = [CCLabelBMFont labelWithString:@"Start Game" fntFile:@"Arial.fnt"];
CCMenuItemLabel *startItem = [CCMenuItemLabel itemWithLabel:startLabel target:self selector:@selector(startGameTapped:)];
startItem.scale = 1; 

CCMenu *menu = [CCMenu menuWithItems:startItem,nil];
[menu alignItemsVerticallyWithPadding:20];
menu.position = ccp( winSize.width/2, winSize.height/2);
[self addChild:menu];

【讨论】:

    【解决方案2】:

    现在您必须实现您在代码中引用的按钮按下处理程序方法 选择器:@selector(starButtonTapped:)

    - (void) starButtonTapped: (CCNode *) sender {
           CCLOG(@"you are here: starButtonTapped");
           // implement your action for button pressing, eg.:
            if (!blLetsJump) {
                blLetsJump = TRUE;
                CCSprite *s = (CCSprite *)[self getChildByTag:100];
                CCSequence *seq = [CCSequence actions:
                                  [CCJumpBy actionWithDuration:1.0 position:CGPointZero height:150 jumps:1],
                                  [CCCallBlock actionWithBlock:
                                  ^{
                                        blLetsJump = FALSE;
                                  }], nil];
                [s runAction:seq];
            }
    }
    

    对于这个跳跃的例子,你必须事先在你的 init 中这样做:

    -(id) init {
        if( (self=[super init]) ) {
            CCSprite *jumpy = [CCSprite spriteWithFile:@"yourjumpinghero.png"];
            jumpy.tag = 100;
            jumpy.position = ccp(160, 50);
            [self addChild:jumpy];
    
           // then add your button
        }
        return self;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-15
      • 2022-11-01
      相关资源
      最近更新 更多