开发者

Subclass Cocos2D MenuItem with Objective-C

I'm using a CCMenu in my small project, it has three buttons in it. I need these buttons to keep triggering if they detect a touch, and as this isn't normal behaviour I decided to subclass the CCMenuItem and override a couple of methods.

The two methods I wish to override are:

-(void) selected
{
    // subclass to change the default action
    if(isEnabled_) { 
        [super selected];
        [self stopActionByTag:kZoomActionTag];
        originalScale_ = self.scale;
        CCAction *zoomAction = [CCScaleTo actionWithDuration:0.1f scale:originalScale_ * 1.2f];
        zoomAction.tag = kZoomActionTag;
        [self runAction:zoomAction];
    }
}

-(void) unselected
{
    // subclass to change the default action
    if(isEnabled_) {
        [super unselected];
        [self stopActionByTag:kZoomActionTag];
        CCAction *zoomAction = [CCScaleTo actionWithDuration:0.1f scale:originalScale_];
        zoomAction.tag = kZoomActionTag;
        [self runAction:zoomAction];
    }
}

So in my subclass I am simply duplicating these exactly, but replace the code inside with the new funct开发者_如何学JAVAionality. To keep it simple, we'll say:

-(void) selected
{
    //turn a sprite around
    mySprite.rotation = 0;
}

-(void) unselected
{
    //turn a sprite around
    mySprite.rotation = 180;
}

Now, the mySprite would be declared in the header of the main body code, which gets imported into this subclass.

The problem is mySprite cannot be seen, it's getting an undeclared error. Instead of mySprite should I be using [super selected]? I have tried this, I get the exact same error.

Thanks.


First of all, yes, you should be using [super selected] if you want it to perform the default behavior for the menu item, rather than just copying the contents of the superclass' function. In the case of the CCMenuItemLabel, which is what you copied, calling [super selected] will allow the label to "do its thing" with respect to the visual effects it does when selected. This allows you to concentrate on what YOU want to do.

As to why your sprite cannot be seen, and what the "undeclared" error might be, it's hard to say without seeing the code. One problem might be that you said you are subclassing CCMenuItem, but are pasting in CCMenuItemLabel code.

Have you tried just watching ccTouchesBegan and ccTouchesEnded directly on your button sprite? Might be more straightforward than trying to force CCMenuItem to do something it wasn't really designed to do...

Failing that, look into "virtual joysticks" and you should get some good sample code. The Cocos2d forums have had at least two major threads on the topic: Thread 1 Thread 2

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜