现在要写场景了。
先新建两个文件TollgateScene.h和TollgateScene.cpp。
h文件的代码如下
#ifndef _TollgateScene_H
#define _TollgateScene_H
#include "cocos2d.h"
USING_NS_CC;
class TollgateScene:public CCLayer
{
CCScene* scene;//源程序中是scene() 不明白什么意思 不应该是变量
CREATE_FUNC(TollgateScene);
void init();
Player* m_player;
CCSprite* m_background1;
CCSprite* m_background2;
}
#endif
但是写完之后,cpp里面实现scene函数的时候出现了不兼容的情况,原来
在h文件里定义完了类要在}之后加上分号。
加上分号之后系统开始纠错,发现了如下
init是初始化函数。正确的写法是virtual bool init();。
由于create了一个m—player,所以要导player.h包。
要使用CREATE_FUNC先要virtual bool init();
然后就是这样
#ifndef _TollgateScene_H
#define _TollgateScene_H
#include "cocos2d.h"
#include "Player.h"
USING_NS_CC;
class TollgateScene:public CCLayer
{
static CCScene* scene();
virtual bool init();
CREATE_FUNC(TollgateScene);
Player* m_player;
CCSprite* m_background1;
CCSprite* m_background2;
};
#endif
cpp文件中,scene函数的功能就是新建一个名为scene的场景,新建一个名为TollgateScene的Layer然后把层加进场景。
出现了一些小的问题,player的CREATE_FUNC不能访问了,原来是player的继承权限没写,要注意继承权限和h文件里函数的权限要不要忘记写。
然后在init里面新建主角和背景精灵,添加到层。
代码如下
#include "TollgateScene.h"
#include "Player.h"
CCScene* TollgateScene::scene()
{
CCScene* scene=CCScene::create();
TollgateScene* layer=TollgateScene::create();
scene->addChild(layer);
return scene;//改的时候加的
}
bool TollgateScene::init()
{
bool bRet = false;
do
{
CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
//创建主角
m_player=Player::create();
m_player->bandSprite(CCSprite::create("sprite.png"));
m_player->setPosition(ccp(visibleSize.width/2,visibleSize.width-50));
this->addChild(m_player);
//背景
m_background1=CCSprite::create("tollgateBG.jpg");
m_background1->setPosition(ccp(0,0));
this->addChild(m_background1);
bRet=true;
} while (0);
return bRet;
}
运行一下 要在AppDelegate.cpp里面改启动场景。
运行显示生成错误,纠结了半个小时,发现少了一句话,在scene函数里,返回值明明是CCScene但是木有写返回值,蛋疼的是,竟然是没有报错的!!就是生成不起来。唉.