游戏入口
WinMain AppDelegate applicationDidFinishLaunching
游戏结构
场景 层 精灵
类
CCObject
CCNode
CCScene、CCLayer、CCSprite、CCMenu
类的基本格式
头文件:
#pragma once
#ifndef __HelloWorld__H__
#define __HelloWorld__H__
#include "cocos2d.h"
#include "Box2D/Box2D.h"
#include "SimpleAudioEngine.h"
class HelloWorld : public cocos2d::CCObject
{
CC_SYNTHESIZE_PASS_BY_REF(std::string, m_userID, UserID);
CC_SYNTHESIZE_PASS_BY_REF(int, m_coin, Coin);
CC_SYNTHESIZE_PASS_BY_REF(int, m_exp, Exp);
CC_SYNTHESIZE_PASS_BY_REF(bool, m_isMusicOn, IsMusicOn);
CC_SYNTHESIZE(bool,drawAimLine,DrawAimLine);
//protected:
// bool drawAimLine;
//public:
// virtual bool getDrawAimLine() const
// {
// return drawAimLine;
// }
// virtual void setDrawAimLine(bool aim)
// {
// drawAimLine = aim;
// }
public:
CREATE_FUNC(HelloWorld);
//static BackgroundLayer* create()
//{
// BackgroundLayer* pRet = new BackgroundLayer();
// if(pRet && pRet->init())
// {
// pRet->autorelease();
// return pRet;
// }
// else
// {
// delete pRet;
// pRet = NULL;
// return NULL;
// }
//}
virtual bool init();
virtual void draw();//继承自CCNode,自定义绘图接口
void visit();
static cocos2d::CCScene* scene();
protected:
UserRecord(const std::string& userID);
bool ccTouchBegan(cocos2d::CCTouch* pTouch, cocos2d::CCEvent* pEvent);
void ccTouchMoved(cocos2d::CCTouch* pTouch, cocos2d::CCEvent* pEvent);
void ccTouchEnded(cocos2d::CCTouch* pTouch, cocos2d::CCEvent* pEvent);
}
#endif
实现文件
#include "HelloWorld.h"
USING_NS_CC;
using namespace std;
HelloWorld::HelloWorld(){
}
void UserRecord::saveToCCUserDefault()
{
char buff[100];
sprintf(buff,"%d %d %d",this->getCoin(),this->getExp(),this->getIsMusicOn() ? 1 : 0);
const char* key = this->getUserID().c_str();
CCUserDefault::sharedUserDefault()->setStringForKey(key,buff);
}
void UserRecord::readFromCCUserDefault()
{
string buff = CCUserDefault::sharedUserDefault()->getStringForKey(this->getUserID().c_str());
int coin = 0;
int experience = 0;
int music = 0;
sscanf(buff.c_str(), "%d %d %d", &coin, &experience, &music);
this->setCoin(coin);
this->setExp(experience);
this->setIsMusicOn(music != 0);
}
void CannonSprite::draw()
{
CCSprite::draw();
if(this->drawAimLine)
{
CCPoint start = ccp(64,128);
CCPoint direction = ccp(0,1);
direction = ccpMult(direction,1024);
CCPoint end = ccpAdd(start,direction);
ccDrawColor4B(255,255,255,255);
ccDrawLine(start,end);
}
}
void LayerTest::draw()
{
static GLfloat vertex[] = {
0.0f, 0.0f, 0.0f,
480.0f, 0.0f, 0.0f,
0.0f, 320.0f, 0.0f,
480.0f, 320.0f, 0.0f,
};
static GLfloat coord[] = {
0.0f, 1.0f,
1.0f, 1.0f,
0.0f, 0.0f,
1.0f, 0.0f,
};
static CCTexture2D* texture2d = NULL;
if(!texture2d)
{
texture2d = CCTextureCache::sharedTextureCache()->addImage("HelloWorld.png");
}
ccGLEnableVertexAttribs(kCCVertexAttribFlag_Position | kCCVertexAttribFlag_TexCoords);
texture2d->getShaderProgram()->use();
texture2d->getShaderProgram()->setUniformForModelViewProjectionMatrix();
glVertexAttribPointer(kCCVertexAttrib_Position,3,GL_FLOAT,GL_FALSE,0,vertex);
glVertexAttribPointer(kCCVertexAttrib_TexCoords,2,GL_FLOAT,GL_FALSE,0,coord);
glDrawArrays(GL_TRIANGLE_STRIP,0,4);
}
bool FishLayer::ccTouchBegan(cocos2d::CCTouch* pTouch, cocos2d::CCEvent* pEvent)
{
CCPoint target = this->locationFromTouch(pTouch);
float angle = ccpAngleSigned(ccpSub(target,ccp(240,0)),ccpSub(ccp(240,100),ccp(240,0)));
pCannon->setDrawAimLine(true);
pCannon->setRotation(CC_RADIANS_TO_DEGREES(angle));//弧度转换为度
return true;
}
遮罩:
void BackgroundLayer::visit()
{
glEnable(GL_SCISSOR_TEST);
glScissor(100,200,200,100);
CCNode::visit();
glDisable(GL_SCISSOR_TEST);
}
截屏:CCRenderTexture
void BackgroundLayer::saveScreen(cocos2d::CCObject* pSender)
{
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
CCRenderTexture* render = CCRenderTexture::create(winSize.width,winSize.height);
render->begin();
CCDirector::sharedDirector()->drawScene();
render->end();
render->saveToFile("MyScreen.png");//默认Resources目录
}
场景切换
CCDirector *pDirector = CCDirector::sharedDirector();
CCScene *pScene = HelloWorld::scene();
pDirector->runWithScene(pScene);
场景切换特效
SecondScene* pSS = SecondScene::create();
//CCDirector::sharedDirector()->replaceScene(CCTransitionPageTurn::transitionWithDuration(2,pSS,false));
//CCDirector::sharedDirector()->replaceScene(CCTransitionJumpZoom::transitionWithDuration(2,pSS));
//CCDirector::sharedDirector()->replaceScene(CCTransitionFade::transitionWithDuration(2,pSS));
//CCDirector::sharedDirector()->replaceScene(CCTransitionFlipX::transitionWithDuration(2,pSS));
//CCDirector::sharedDirector()->replaceScene(CCTransitionShrinkGrow::transitionWithDuration(2,pSS));
//CCDirector::sharedDirector()->replaceScene(CCTransitionMoveInL::transitionWithDuration(2,pSS));
//CCDirector::sharedDirector()->replaceScene(CCTransitionRotoZoom::transitionWithDuration(2,pSS));
CCDirector::sharedDirector()->replaceScene(CCTransitionFadeDown::transitionWithDuration(2,pSS));
系统内置的层:CCLayerColor、CCLayerGradient
pLayerColor = CCLayerColor::create(ccc4(0x00,0x00,0xff,0xff),200,200);
pLayerColor->setPosition(100,100);
this->addChild(pLayerColor);
CCLayerGradient* pLayerGradient = CCLayerGradient::create(ccc4(0xff,0x00,0x00,0xff),ccc4(0x00,0xff,0x00,0xff));
this->addChild(pLayerGradient);
常用的一个方法是,(只创建Layer,继承于 : public cocos2d::CCLayer)
CCScene* HelloWorld::scene()
{
CCScene * scene = NULL;
do
{
scene = CCScene::create();
HelloWorld *layer = HelloWorld::create();
scene->addChild(layer);
} while (0);
return scene;
}
创建精灵
CCSprite* pSprite = CCSprite::create("HelloWorld.png");
pSprite->setPosition(ccp(size.width/2, size.height/2));
this->addChild(pSprite, 0);
创建菜单(图片菜单、文字菜单)
CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
this,
menu_selector(HelloWorld::menuCloseCallback));
pCloseItem->setPosition(ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20));
CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
pMenu->setPosition(CCPointZero)
this->addChild(pMenu, 1);
CCMenuItemSprite* mi = CCMenuItemSprite::create(
CCSprite::create("button_camera.png"),
CCSprite::create("button_camera.png"),
this,
menu_selector(BackgroundLayer::saveScreen));
CCMenu* menu = CCMenu::create(mi,NULL);
menu->setPosition(30, winSize.height - 40);
this->addChild(menu);
创建lable
CCLabelTTF* pMyLabel = CCLabelTTF::create("My Hello World","Chiller",36);
pMyLabel->setPosition(ccp(240,30));
this->addChild(pMyLabel);
//碎图压缩文件
CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("all.plist");
CCArray* fishFrames = CCArray::createWithCapacity(8);
for(int i=0; i<8; i++)
{
CCString* filename = CCString::createWithFormat("fish_%d.png", i);
CCSpriteFrame* fishFrame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(filename->getCString());
fishFrames->addObject(fishFrame);
}
CCAnimation* fishAnimation = CCAnimation::createWithSpriteFrames(fishFrames);
fishAnimation->setDelayPerUnit(0.15f);
CCAnimationCache::sharedAnimationCache()->addAnimation(fishAnimation,"fish_animation");
// create a scene. it's an autorelease object
//CCScene *pScene = HelloWorld::scene();
SimpleAudioEngine::sharedEngine()->preloadBackgroundMusic("bg_music.mp3");
SimpleAudioEngine::sharedEngine()->preloadEffect("sound_shot.mp3");
纹理
OpenGL在显存中保存的纹理的长度、宽度像素数是2的幂。
2、4、6、8、16、32、64、128、256、512、1024、2048、4096、…
地图:
//加载tmx文件
CCTMXTiledMap* pTileMap = CCTMXTiledMap::create("theMap.tmx");//地图文件
this->addChild(pTileMap);
//根据名子获取层
CCTMXLayer* eventLayer = [tileMap layerNamed:@"GameEventLayer"];
eventLayer.visible = NO;
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
//CCSprite* background = CCSprite::create("bj01.jpg");
CCSprite* background = CCSprite::createWithSpriteFrameName("bk.jpg");
background->setPosition(CCPointMake(winSize.width*0.5,winSize.height*0.5));
this->addChild(background);
动作
CCActionInterval* ai;
//ai = CCMoveTo::create(2,ccp(100,100));
//pFish->runAction(ai);
//ai = CCMoveBy::create(2,ccp(50,50));
//pFish->runAction(ai);
//ai = CCScaleTo::create(2.0f,2.0f,2.0f);
//pFish->runAction(ai);
//ai = CCRotateBy::create(2.0f,90.0f);
//pFish->runAction(ai);
//ai = CCJumpTo::create(2,ccp(90,160),20,3);
//pFish->runAction(ai);
//ai = CCFadeOut::create(2.0f);
//pFish->runAction(ai);
//CCFiniteTimeAction* fta = CCHide::create();
//pFish->runAction(fta);
//ai = CCBlink::create(2,10);
//pFish->runAction(ai);
//ai = CCTintTo::create(2,255,0,0);
//pFish->runAction(ai);
//CCFiniteTimeAction* fta = CCFlipX::create(true);
//pFish->runAction(fta);
//ccBezierConfig bezier;
//bezier.controlPoint_1 = ccp(230,60);
//bezier.controlPoint_2 = ccp(60,270);
//bezier.endPosition = ccp(50,160);
//ai = CCBezierTo::create(3,bezier);
//pFish->runAction(ai);
CCActionInterval* move1 = CCMoveTo::create(2,ccp(-190,160));
CCFiniteTimeAction* flipToRight = CCFlipX::create(true);
CCActionInterval* move2 = CCMoveTo::create(4,ccp(700,160));
CCFiniteTimeAction* flipToLeft = CCFlipX::create(false);
CCActionInterval* move3 = CCMoveTo::create(2,ccp(240,160));
CCAction* action = CCRepeatForever::create((CCActionInterval*)CCSequence::create(move1,flipToRight,move2,flipToLeft,move3,NULL));
pFish->runAction(action);
//纹理
CCTexture2D* texture = CCTextureCache::sharedTextureCache()->addImage("marlins.png");
float w = texture->getContentSize().width;
float h = texture->getContentSize().height / 10;
CCAnimation* animation = CCAnimation::create();
animation->setDelayPerUnit(0.15f);
for(int i=0; i<10; i++)
animation->addSpriteFrameWithTexture(texture, CCRectMake(0,i*h,w,h));
CCAnimate* animate = CCAnimate::create(animation);
pFish->runAction(CCRepeatForever::create(animate));
//CCSpriteBatchNode *pBatchNode = CCSpriteBatchNode::create("all.png");
//pBatchNode->setPosition(CCPointZero);
//this->addChild(pBatchNode);
//for(int i=0; i<30; i++)
//{
// CCSprite* redFish = CCSprite::createWithSpriteFrameName("fish_0.png");
// int x = CCRANDOM_0_1() * 480;
// int y = CCRANDOM_0_1() * 320;
// redFish->setPosition(ccp(x,y));
// //this->addChild(redFish);
// pBatchNode->addChild(redFish);
// CCAnimate* redFishAnimate = CCAnimate::create(CCAnimationCache::sharedAnimationCache()->animationByName("fish_animation"));
// redFish->runAction(CCRepeatForever::create(redFishAnimate));
//}
//CCSpriteBatchNode* pBatchNode = CCSpriteBatchNode::create("sea_star_32.png");
//this->addChild(pBatchNode);
//for(int i=0; i<30; i++)
//{
// CCSprite* pSeaStar = CCSprite::createWithTexture(pBatchNode->getTexture());
// int x = CCRANDOM_0_1() * 480;
// int y = CCRANDOM_0_1() * 320;
// pSeaStar->setPosition(ccp(x,y));
// //this->addChild(pSeaStar);
// pBatchNode->addChild(pSeaStar);
//}
//CCSprite* pCannon = CCSprite::create("cannon.png");
pCannon = CannonSprite::create();
pCannon->initWithCannonImage();
pCannon->setPosition(ccp(240,0));
pCannon->setScale(0.5f);
pCannon->setAnchorPoint(ccp(0.5,0.25));
pCannon->setDrawAimLine(false);
this->addChild(pCannon);
定时器
//this->schedule(schedule_selector(FishLayer::moveFish));
游戏主循环
瓦片地图:Tile Map
编辑器Tile Map Editor
火、爆炸、烟、水流、火花、落叶、云、雾、雪、尘、流星、星云、…
粒子系统: 基类CCParticleSystem、子类CCParticleSystemQuad
Cocos2d-x内置的粒子效果:
CCParticleExplosion CCParticleFireworks
CCParticleFire CCParticleFlower
CCParticleGalaxy CCParticleMeteor
CCParticleSpiral CCParticleSnow
CCParticleSmoke CCParticleSun
CCParticleRain
粒子效果编辑器:Particle Designer
CCParticleSystem* particle = CCParticleSnow::node();
particle->setTexture(CCTextureCache::sharedTextureCache()->addImage("snow.png"));
pScene->addChild(particle);
CCParticleSystemQuad* system = new CCParticleSystemQuad();
system->initWithFile("SpinningPeas.plist");
system->setTextureWithRect(CCTextureCache::sharedTextureCache()->addImage("particles.png"),CCRectMake(0,0,32,32));
pScene->addChild(system,10);
向量计算
夹角计算
碎图压缩:TexturePacker
精灵:CCSpriteFrame、CCSpriteFrameCache
批量渲染:CCSpriteBatchNode
Bezier曲线
波纹动作
触摸分发器:分发器->委托对象->委托对象->委托对象->
标准触摸事件: CCStandardTouchDelegate
目标触摸事件: CCTargetedDelegate
触摸回调函数:ccTouchBegan、ccTouchMoved、ccTouchEnded、ccTouchCancelled
游戏脚本:Lua 语言
声音引擎(音乐、音效)
SimpleAudioEngine::sharedEngine()->playBackgroundMusic("bg_music.mp3");
SimpleAudioEngine::sharedEngine()->stopBackgroundMusic();
SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
SimpleAudioEngine::sharedEngine()->playEffect("sound_shot.mp3");
1、物理引擎Box2D
b2Word ——> 世界、物理世界
b2Body ——> 物体、刚体
bFixture ——> 夹具
bShape ——> 形状
刚体
英文:rigid body
定义:实际固体的理想化模型,即在受力后其大小、形状和内部各点相对位置都保持不变的物体。
b2Vec2 gravity;
gravity.Set(0.0f,-10.0f);
world = new b2World(gravity);
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0,0);
b2Body* groundBody = world->CreateBody(&groundBodyDef);
b2EdgeShape groundBox;
//bottom
groundBox.Set(b2Vec2(0,0),b2Vec2(winSize.width/PTM_RATIO,0));
groundBody->CreateFixture(&groundBox,0);
//top
groundBox.Set(b2Vec2(0,winSize.height/PTM_RATIO),b2Vec2(winSize.width/PTM_RATIO,winSize.height/PTM_RATIO));
groundBody->CreateFixture(&groundBox,0);
//left
groundBox.Set(b2Vec2(0,winSize.height/PTM_RATIO),b2Vec2(0,0));
groundBody->CreateFixture(&groundBox,0);
//right
groundBox.Set(b2Vec2(winSize.width/PTM_RATIO,winSize.height/PTM_RATIO),b2Vec2(winSize.width/PTM_RATIO,0));
groundBody->CreateFixture(&groundBox,0);
this->setTouchEnabled(true);
this->scheduleUpdate();
void MyLayer::update(float dt)
{
int32 velocityIterations = 8;
int32 positionIterations = 1;
world->Step(dt,velocityIterations,positionIterations);
for(b2Body *b = world->GetBodyList();b;b=b->GetNext())
{
if(b->GetUserData() != NULL)
{
CCSprite* myActor = (CCSprite*)b->GetUserData();
myActor->setPosition(ccp((b->GetPosition().x)*PTM_RATIO,b->GetPosition().y*PTM_RATIO));
myActor->setRotation(-1*CC_RADIANS_TO_DEGREES(b->GetAngle()));
}
}
}
1、数据存储CCUserDefault(可以操作int、float、double、bool、string)
(可以格式化成一个字符串存储)
int gold = CCUserDefault::sharedUserDefault()->getIntegerForKey("gold",100);
CCString game_level = CCUserDefault::sharedUserDefault()->getStringForKey("GameLevel","Easy");
CCUserDefault::sharedUserDefault()->setIntegerForKey("gold",200);
CCUserDefault::sharedUserDefault()->setStringForKey("GameLevel","Hard");
可视化开发工具:CocosBuilder 、 CocosStudio
游戏美工:
UI编辑器
动画编辑器
游戏策划:
场景编辑器
数据编辑器
相关方法
alignItemsVerticallyWithPadding(10)
WinMain AppDelegate applicationDidFinishLaunching
游戏结构
场景 层 精灵
类
CCObject
CCNode
CCScene、CCLayer、CCSprite、CCMenu
类的基本格式
头文件:
#pragma once
#ifndef __HelloWorld__H__
#define __HelloWorld__H__
#include "cocos2d.h"
#include "Box2D/Box2D.h"
#include "SimpleAudioEngine.h"
class HelloWorld : public cocos2d::CCObject
{
CC_SYNTHESIZE_PASS_BY_REF(std::string, m_userID, UserID);
CC_SYNTHESIZE_PASS_BY_REF(int, m_coin, Coin);
CC_SYNTHESIZE_PASS_BY_REF(int, m_exp, Exp);
CC_SYNTHESIZE_PASS_BY_REF(bool, m_isMusicOn, IsMusicOn);
CC_SYNTHESIZE(bool,drawAimLine,DrawAimLine);
//protected:
// bool drawAimLine;
//public:
// virtual bool getDrawAimLine() const
// {
// return drawAimLine;
// }
// virtual void setDrawAimLine(bool aim)
// {
// drawAimLine = aim;
// }
public:
CREATE_FUNC(HelloWorld);
//static BackgroundLayer* create()
//{
// BackgroundLayer* pRet = new BackgroundLayer();
// if(pRet && pRet->init())
// {
// pRet->autorelease();
// return pRet;
// }
// else
// {
// delete pRet;
// pRet = NULL;
// return NULL;
// }
//}
virtual bool init();
virtual void draw();//继承自CCNode,自定义绘图接口
void visit();
static cocos2d::CCScene* scene();
protected:
UserRecord(const std::string& userID);
bool ccTouchBegan(cocos2d::CCTouch* pTouch, cocos2d::CCEvent* pEvent);
void ccTouchMoved(cocos2d::CCTouch* pTouch, cocos2d::CCEvent* pEvent);
void ccTouchEnded(cocos2d::CCTouch* pTouch, cocos2d::CCEvent* pEvent);
}
#endif
实现文件
#include "HelloWorld.h"
USING_NS_CC;
using namespace std;
HelloWorld::HelloWorld(){
}
void UserRecord::saveToCCUserDefault()
{
char buff[100];
sprintf(buff,"%d %d %d",this->getCoin(),this->getExp(),this->getIsMusicOn() ? 1 : 0);
const char* key = this->getUserID().c_str();
CCUserDefault::sharedUserDefault()->setStringForKey(key,buff);
}
void UserRecord::readFromCCUserDefault()
{
string buff = CCUserDefault::sharedUserDefault()->getStringForKey(this->getUserID().c_str());
int coin = 0;
int experience = 0;
int music = 0;
sscanf(buff.c_str(), "%d %d %d", &coin, &experience, &music);
this->setCoin(coin);
this->setExp(experience);
this->setIsMusicOn(music != 0);
}
void CannonSprite::draw()
{
CCSprite::draw();
if(this->drawAimLine)
{
CCPoint start = ccp(64,128);
CCPoint direction = ccp(0,1);
direction = ccpMult(direction,1024);
CCPoint end = ccpAdd(start,direction);
ccDrawColor4B(255,255,255,255);
ccDrawLine(start,end);
}
}
void LayerTest::draw()
{
static GLfloat vertex[] = {
0.0f, 0.0f, 0.0f,
480.0f, 0.0f, 0.0f,
0.0f, 320.0f, 0.0f,
480.0f, 320.0f, 0.0f,
};
static GLfloat coord[] = {
0.0f, 1.0f,
1.0f, 1.0f,
0.0f, 0.0f,
1.0f, 0.0f,
};
static CCTexture2D* texture2d = NULL;
if(!texture2d)
{
texture2d = CCTextureCache::sharedTextureCache()->addImage("HelloWorld.png");
}
ccGLEnableVertexAttribs(kCCVertexAttribFlag_Position | kCCVertexAttribFlag_TexCoords);
texture2d->getShaderProgram()->use();
texture2d->getShaderProgram()->setUniformForModelViewProjectionMatrix();
glVertexAttribPointer(kCCVertexAttrib_Position,3,GL_FLOAT,GL_FALSE,0,vertex);
glVertexAttribPointer(kCCVertexAttrib_TexCoords,2,GL_FLOAT,GL_FALSE,0,coord);
glDrawArrays(GL_TRIANGLE_STRIP,0,4);
}
bool FishLayer::ccTouchBegan(cocos2d::CCTouch* pTouch, cocos2d::CCEvent* pEvent)
{
CCPoint target = this->locationFromTouch(pTouch);
float angle = ccpAngleSigned(ccpSub(target,ccp(240,0)),ccpSub(ccp(240,100),ccp(240,0)));
pCannon->setDrawAimLine(true);
pCannon->setRotation(CC_RADIANS_TO_DEGREES(angle));//弧度转换为度
return true;
}
遮罩:
void BackgroundLayer::visit()
{
glEnable(GL_SCISSOR_TEST);
glScissor(100,200,200,100);
CCNode::visit();
glDisable(GL_SCISSOR_TEST);
}
截屏:CCRenderTexture
void BackgroundLayer::saveScreen(cocos2d::CCObject* pSender)
{
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
CCRenderTexture* render = CCRenderTexture::create(winSize.width,winSize.height);
render->begin();
CCDirector::sharedDirector()->drawScene();
render->end();
render->saveToFile("MyScreen.png");//默认Resources目录
}
场景切换
CCDirector *pDirector = CCDirector::sharedDirector();
CCScene *pScene = HelloWorld::scene();
pDirector->runWithScene(pScene);
场景切换特效
SecondScene* pSS = SecondScene::create();
//CCDirector::sharedDirector()->replaceScene(CCTransitionPageTurn::transitionWithDuration(2,pSS,false));
//CCDirector::sharedDirector()->replaceScene(CCTransitionJumpZoom::transitionWithDuration(2,pSS));
//CCDirector::sharedDirector()->replaceScene(CCTransitionFade::transitionWithDuration(2,pSS));
//CCDirector::sharedDirector()->replaceScene(CCTransitionFlipX::transitionWithDuration(2,pSS));
//CCDirector::sharedDirector()->replaceScene(CCTransitionShrinkGrow::transitionWithDuration(2,pSS));
//CCDirector::sharedDirector()->replaceScene(CCTransitionMoveInL::transitionWithDuration(2,pSS));
//CCDirector::sharedDirector()->replaceScene(CCTransitionRotoZoom::transitionWithDuration(2,pSS));
CCDirector::sharedDirector()->replaceScene(CCTransitionFadeDown::transitionWithDuration(2,pSS));
系统内置的层:CCLayerColor、CCLayerGradient
pLayerColor = CCLayerColor::create(ccc4(0x00,0x00,0xff,0xff),200,200);
pLayerColor->setPosition(100,100);
this->addChild(pLayerColor);
CCLayerGradient* pLayerGradient = CCLayerGradient::create(ccc4(0xff,0x00,0x00,0xff),ccc4(0x00,0xff,0x00,0xff));
this->addChild(pLayerGradient);
常用的一个方法是,(只创建Layer,继承于 : public cocos2d::CCLayer)
CCScene* HelloWorld::scene()
{
CCScene * scene = NULL;
do
{
scene = CCScene::create();
HelloWorld *layer = HelloWorld::create();
scene->addChild(layer);
} while (0);
return scene;
}
创建精灵
CCSprite* pSprite = CCSprite::create("HelloWorld.png");
pSprite->setPosition(ccp(size.width/2, size.height/2));
this->addChild(pSprite, 0);
创建菜单(图片菜单、文字菜单)
CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
this,
menu_selector(HelloWorld::menuCloseCallback));
pCloseItem->setPosition(ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20));
CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
pMenu->setPosition(CCPointZero)
this->addChild(pMenu, 1);
CCMenuItemSprite* mi = CCMenuItemSprite::create(
CCSprite::create("button_camera.png"),
CCSprite::create("button_camera.png"),
this,
menu_selector(BackgroundLayer::saveScreen));
CCMenu* menu = CCMenu::create(mi,NULL);
menu->setPosition(30, winSize.height - 40);
this->addChild(menu);
创建lable
CCLabelTTF* pMyLabel = CCLabelTTF::create("My Hello World","Chiller",36);
pMyLabel->setPosition(ccp(240,30));
this->addChild(pMyLabel);
//碎图压缩文件
CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("all.plist");
CCArray* fishFrames = CCArray::createWithCapacity(8);
for(int i=0; i<8; i++)
{
CCString* filename = CCString::createWithFormat("fish_%d.png", i);
CCSpriteFrame* fishFrame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(filename->getCString());
fishFrames->addObject(fishFrame);
}
CCAnimation* fishAnimation = CCAnimation::createWithSpriteFrames(fishFrames);
fishAnimation->setDelayPerUnit(0.15f);
CCAnimationCache::sharedAnimationCache()->addAnimation(fishAnimation,"fish_animation");
// create a scene. it's an autorelease object
//CCScene *pScene = HelloWorld::scene();
SimpleAudioEngine::sharedEngine()->preloadBackgroundMusic("bg_music.mp3");
SimpleAudioEngine::sharedEngine()->preloadEffect("sound_shot.mp3");
纹理
OpenGL在显存中保存的纹理的长度、宽度像素数是2的幂。
2、4、6、8、16、32、64、128、256、512、1024、2048、4096、…
地图:
//加载tmx文件
CCTMXTiledMap* pTileMap = CCTMXTiledMap::create("theMap.tmx");//地图文件
this->addChild(pTileMap);
//根据名子获取层
CCTMXLayer* eventLayer = [tileMap layerNamed:@"GameEventLayer"];
eventLayer.visible = NO;
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
//CCSprite* background = CCSprite::create("bj01.jpg");
CCSprite* background = CCSprite::createWithSpriteFrameName("bk.jpg");
background->setPosition(CCPointMake(winSize.width*0.5,winSize.height*0.5));
this->addChild(background);
动作
CCActionInterval* ai;
//ai = CCMoveTo::create(2,ccp(100,100));
//pFish->runAction(ai);
//ai = CCMoveBy::create(2,ccp(50,50));
//pFish->runAction(ai);
//ai = CCScaleTo::create(2.0f,2.0f,2.0f);
//pFish->runAction(ai);
//ai = CCRotateBy::create(2.0f,90.0f);
//pFish->runAction(ai);
//ai = CCJumpTo::create(2,ccp(90,160),20,3);
//pFish->runAction(ai);
//ai = CCFadeOut::create(2.0f);
//pFish->runAction(ai);
//CCFiniteTimeAction* fta = CCHide::create();
//pFish->runAction(fta);
//ai = CCBlink::create(2,10);
//pFish->runAction(ai);
//ai = CCTintTo::create(2,255,0,0);
//pFish->runAction(ai);
//CCFiniteTimeAction* fta = CCFlipX::create(true);
//pFish->runAction(fta);
//ccBezierConfig bezier;
//bezier.controlPoint_1 = ccp(230,60);
//bezier.controlPoint_2 = ccp(60,270);
//bezier.endPosition = ccp(50,160);
//ai = CCBezierTo::create(3,bezier);
//pFish->runAction(ai);
CCActionInterval* move1 = CCMoveTo::create(2,ccp(-190,160));
CCFiniteTimeAction* flipToRight = CCFlipX::create(true);
CCActionInterval* move2 = CCMoveTo::create(4,ccp(700,160));
CCFiniteTimeAction* flipToLeft = CCFlipX::create(false);
CCActionInterval* move3 = CCMoveTo::create(2,ccp(240,160));
CCAction* action = CCRepeatForever::create((CCActionInterval*)CCSequence::create(move1,flipToRight,move2,flipToLeft,move3,NULL));
pFish->runAction(action);
//纹理
CCTexture2D* texture = CCTextureCache::sharedTextureCache()->addImage("marlins.png");
float w = texture->getContentSize().width;
float h = texture->getContentSize().height / 10;
CCAnimation* animation = CCAnimation::create();
animation->setDelayPerUnit(0.15f);
for(int i=0; i<10; i++)
animation->addSpriteFrameWithTexture(texture, CCRectMake(0,i*h,w,h));
CCAnimate* animate = CCAnimate::create(animation);
pFish->runAction(CCRepeatForever::create(animate));
//CCSpriteBatchNode *pBatchNode = CCSpriteBatchNode::create("all.png");
//pBatchNode->setPosition(CCPointZero);
//this->addChild(pBatchNode);
//for(int i=0; i<30; i++)
//{
// CCSprite* redFish = CCSprite::createWithSpriteFrameName("fish_0.png");
// int x = CCRANDOM_0_1() * 480;
// int y = CCRANDOM_0_1() * 320;
// redFish->setPosition(ccp(x,y));
// //this->addChild(redFish);
// pBatchNode->addChild(redFish);
// CCAnimate* redFishAnimate = CCAnimate::create(CCAnimationCache::sharedAnimationCache()->animationByName("fish_animation"));
// redFish->runAction(CCRepeatForever::create(redFishAnimate));
//}
//CCSpriteBatchNode* pBatchNode = CCSpriteBatchNode::create("sea_star_32.png");
//this->addChild(pBatchNode);
//for(int i=0; i<30; i++)
//{
// CCSprite* pSeaStar = CCSprite::createWithTexture(pBatchNode->getTexture());
// int x = CCRANDOM_0_1() * 480;
// int y = CCRANDOM_0_1() * 320;
// pSeaStar->setPosition(ccp(x,y));
// //this->addChild(pSeaStar);
// pBatchNode->addChild(pSeaStar);
//}
//CCSprite* pCannon = CCSprite::create("cannon.png");
pCannon = CannonSprite::create();
pCannon->initWithCannonImage();
pCannon->setPosition(ccp(240,0));
pCannon->setScale(0.5f);
pCannon->setAnchorPoint(ccp(0.5,0.25));
pCannon->setDrawAimLine(false);
this->addChild(pCannon);
定时器
//this->schedule(schedule_selector(FishLayer::moveFish));
游戏主循环
瓦片地图:Tile Map
编辑器Tile Map Editor
火、爆炸、烟、水流、火花、落叶、云、雾、雪、尘、流星、星云、…
粒子系统: 基类CCParticleSystem、子类CCParticleSystemQuad
Cocos2d-x内置的粒子效果:
CCParticleExplosion CCParticleFireworks
CCParticleFire CCParticleFlower
CCParticleGalaxy CCParticleMeteor
CCParticleSpiral CCParticleSnow
CCParticleSmoke CCParticleSun
CCParticleRain
粒子效果编辑器:Particle Designer
CCParticleSystem* particle = CCParticleSnow::node();
particle->setTexture(CCTextureCache::sharedTextureCache()->addImage("snow.png"));
pScene->addChild(particle);
CCParticleSystemQuad* system = new CCParticleSystemQuad();
system->initWithFile("SpinningPeas.plist");
system->setTextureWithRect(CCTextureCache::sharedTextureCache()->addImage("particles.png"),CCRectMake(0,0,32,32));
pScene->addChild(system,10);
向量计算
夹角计算
碎图压缩:TexturePacker
精灵:CCSpriteFrame、CCSpriteFrameCache
批量渲染:CCSpriteBatchNode
Bezier曲线
波纹动作
触摸分发器:分发器->委托对象->委托对象->委托对象->
标准触摸事件: CCStandardTouchDelegate
目标触摸事件: CCTargetedDelegate
触摸回调函数:ccTouchBegan、ccTouchMoved、ccTouchEnded、ccTouchCancelled
游戏脚本:Lua 语言
声音引擎(音乐、音效)
SimpleAudioEngine::sharedEngine()->playBackgroundMusic("bg_music.mp3");
SimpleAudioEngine::sharedEngine()->stopBackgroundMusic();
SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
SimpleAudioEngine::sharedEngine()->playEffect("sound_shot.mp3");
1、物理引擎Box2D
b2Word ——> 世界、物理世界
b2Body ——> 物体、刚体
bFixture ——> 夹具
bShape ——> 形状
刚体
英文:rigid body
定义:实际固体的理想化模型,即在受力后其大小、形状和内部各点相对位置都保持不变的物体。
b2Vec2 gravity;
gravity.Set(0.0f,-10.0f);
world = new b2World(gravity);
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0,0);
b2Body* groundBody = world->CreateBody(&groundBodyDef);
b2EdgeShape groundBox;
//bottom
groundBox.Set(b2Vec2(0,0),b2Vec2(winSize.width/PTM_RATIO,0));
groundBody->CreateFixture(&groundBox,0);
//top
groundBox.Set(b2Vec2(0,winSize.height/PTM_RATIO),b2Vec2(winSize.width/PTM_RATIO,winSize.height/PTM_RATIO));
groundBody->CreateFixture(&groundBox,0);
//left
groundBox.Set(b2Vec2(0,winSize.height/PTM_RATIO),b2Vec2(0,0));
groundBody->CreateFixture(&groundBox,0);
//right
groundBox.Set(b2Vec2(winSize.width/PTM_RATIO,winSize.height/PTM_RATIO),b2Vec2(winSize.width/PTM_RATIO,0));
groundBody->CreateFixture(&groundBox,0);
this->setTouchEnabled(true);
this->scheduleUpdate();
void MyLayer::update(float dt)
{
int32 velocityIterations = 8;
int32 positionIterations = 1;
world->Step(dt,velocityIterations,positionIterations);
for(b2Body *b = world->GetBodyList();b;b=b->GetNext())
{
if(b->GetUserData() != NULL)
{
CCSprite* myActor = (CCSprite*)b->GetUserData();
myActor->setPosition(ccp((b->GetPosition().x)*PTM_RATIO,b->GetPosition().y*PTM_RATIO));
myActor->setRotation(-1*CC_RADIANS_TO_DEGREES(b->GetAngle()));
}
}
}
1、数据存储CCUserDefault(可以操作int、float、double、bool、string)
(可以格式化成一个字符串存储)
int gold = CCUserDefault::sharedUserDefault()->getIntegerForKey("gold",100);
CCString game_level = CCUserDefault::sharedUserDefault()->getStringForKey("GameLevel","Easy");
CCUserDefault::sharedUserDefault()->setIntegerForKey("gold",200);
CCUserDefault::sharedUserDefault()->setStringForKey("GameLevel","Hard");
可视化开发工具:CocosBuilder 、 CocosStudio
游戏美工:
UI编辑器
动画编辑器
游戏策划:
场景编辑器
数据编辑器
相关方法
alignItemsVerticallyWithPadding(10)