我在cocos2d有2年的经验,但今天开始使用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);
答案 0 :(得分:2)
添加重要内容:
在MyButton类中,您没有create方法。你所做的只是创建一个CCMenuItemSprite实例并将其转换为一个按钮。这是错的。
您应该在MyButton
public static 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;
}
答案 1 :(得分:2)
将onEnter()
和selected()
声明为virtual
。 onEnter()
和selected()
是来自CCMenuItemSprite
的派生方法,因此需要将它们声明为virtual
以覆盖它们。如果未覆盖,您的应用会调用CCMenuItemSprite::onEnter()
而非MyButton::onEnter()
。
尝试详细了解here
#include "cocos2d.h"
using namespace cocos2d;
class MyButton : public CCMenuItemSprite {
public:
virtual void onEnter();
virtual void selected();
};