我有2年的cocos2d工作经验,但今天开始学习cocos2d-x。我只是写了派生的菜单按钮类,它没有触发任何默认方法,如onEnter,selected和all。
这是我的代码:
//MyButton.h
#include <stddef.h>
#include "cocos2d.h"
using namespace cocos2d;
class MyButton : public CCMenuItemSprite
{
public:
void onEnter();
void selected();
};
//MyButton.mm
void MyButton::onEnter()
{
CCPoint pos = this->getSelectedImage()->getPosition();
CCSize size = this->getSelectedImage()->getContentSize();
this->getSelectedImage()->setPosition(ccp(pos.x+size.width*0.5f, pos.y+size.height*0.5f));
this->getSelectedImage()->setAnchorPoint(ccp(0.5f,0.5f));
}
void MyButton::selected()
{
if (isEnabled())
{
if (this->getSelectedImage())
{
CCScaleTo *scale = CCScaleTo::create(0.5f, 1.3f);
this->getSelectedImage()->runAction(scale);
}
}
}
MyButton * MyButton::create(CCNode* normalSprite, CCNode* selectedSprite, CCObject* target, SEL_MenuHandler selector)
{
MyButton *btn = (MyButton*)CCMenuItemSprite::create(normalSprite, selectedSprite,target, selector);
return btn;
}
//这里是创建按钮的代码
CCSprite *start_1 = CCSprite::createWithSpriteFrameName(FRAME_MM_START);
CCSprite *start_2 = CCSprite::createWithSpriteFrameName(FRAME_MM_START);
MyButton *btnPlay =(MyButton*) MyButton::create(start_1,
start_2,
this,
menu_selector(MyMainMenu::playGame));
btnPlay->setPosition(ccp(mS.width*0.5f, mS.height*0.5f));
btnPlay->mMaxScale = 1.2f;
CCMenu* menu = CCMenu::create();
menu->setAnchorPoint( ccp(0,0) );
menu->setPosition( ccp(0,0) );
this->addChild(menu, 1);
menu->addChild(btnPlay);
最佳答案
添加重要的内容:
在MyButton类中,没有create方法。您所做的只是创建一个CCMenuItemSprite实例并将其强制转换为按钮。这是错误的。
您应该在MyButton
中添加一些内容
公共静态MyButton * create(CCSprite * normal_sprite,CCSprite * selected_sprite,...);
请以CCMenuItemSprite
类为例。
第一个问题,CCMenuItemSprite::onEnter()
是虚拟的吗?
第二,我猜你的onEnter应该看起来像下面
void MyButton::onEnter()
{
CCMenuItemSprite::onEnter();
CCPoint pos = this->getSelectedImage()->getPosition();
CCSize size = this->getSelectedImage()->getContentSize();
this->getSelectedImage()->setPosition(ccp(pos.x+size.width*0.5f, pos.y+size.height*0.5f));
this->getSelectedImage()->setAnchorPoint(ccp(0.5f,0.5f));
}
这就是c ++的工作方式。它与Objective-C不同,后者默认情况下允许方法重载。
MyButton * MyButton::create(CCNode* normalSprite, CCNode* selectedSprite, CCObject* target, SEL_MenuHandler selector)
{
MyButton *pRet = new MyButton();
pRet->initWithNormalSprite(normalSprite, selectedSprite, null, target, selector);
pRet->autorelease();
return pRet;
}
关于iphone - Cocos2d-x onEnter和其他默认方法未调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17027837/