坑爹啊,cocos2dx对象实例化的问题。
本帖最后由 u010232872 于 2013-11-05 16:50:07 编辑 事情是这样的。游戏的主场景
绘制主角
hero = new GameObjHero();
hero->setScale(0.5);
hero->setPosition(ccp(100,160));
addChild(hero,1);
然后我们来看GameObjHero是怎么定义的。
GameObjHero::GameObjHero(void)
{
}
GameObjHero::~GameObjHero(void)
{
}
void GameObjHero::onEnter()
{
CCNode::onEnter();
this->setContentSize(CCSizeMake(85,90));
CCDirector* pDirector = CCDirector::sharedDirector();
pDirector->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
CCSprite * obj = CCSprite::create("s_hurt.png");
hurt = obj->getTexture();
obj = CCSprite::create("s_jump.png");
jump = obj->getTexture();
mainsprite = CCSprite::create("s_1.png");
//动画
CCAnimation * animation = CCAnimation::create();
animation->addSpriteFrameWithFileName("s_1.png");
animation->addSpriteFrameWithFileName("s_2.png");
animation->addSpriteFrameWithFileName("s_3.png");
animation->addSpriteFrameWithFileName("s_4.png");
animation->addSpriteFrameWithFileName("s_5.png");
animation->addSpriteFrameWithFileName("s_6.png");
animation->setDelayPerUnit(0.1f);
animation->setRestoreOriginalFrame(true);
//运行奔跑动画
mainsprite->runAction(CCRepeatForever::create(CCAnimate::create(animation)));
state = 0;
addChild(mainsprite);
}
这几个函数都没有返回值,他啥就能实例化对象到hero了?我好纳闷啊。而且这个GameObjHero函数是空的。怎么神奇的让hero有了活力了,如果是onEnter返回一个精灵对象也罢了,问题是onEnter也没返回啥啊,我自己按照他这样子写,连onEnter都没执行。越想越不明白了。
[解决办法]
是不是那里调用的没有看到阿?
再单步试试!
[解决办法]
一般这种你看看头文件是否有包含Create或者Init的宏或者静态函数
COCO一般都是这么干的
[解决办法]
如果你想问onEnter是怎么调用的 这种就是重载的奥妙了.
onEnter是虚函数 当调用指针的OnEnter时 就会调改指针实例化的那个对象实现的那个onEnter
注意到CCDirector::setNextScene 里面有 m_pRunningScene->onEnter();
而 CCNode::onEnter() 会遍历全部child的节点
arrayMakeObjectsPerformSelector(m_pChildren, onEnter, CCNode*);
来迭代所有的onEnter
你找到setNextScene的调用位置就能解释 为什么onEnter自动被调用了