gpt4 book ai didi

iphone - Cocos2d-x onEnter等默认方法未调用

转载 作者:行者123 更新时间:2023-12-03 20:40:51 25 4
gpt4 key购买 nike

我有 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中添加一些内容

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 不同,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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com