cocos2d-x 2.14默认项目注释
2013-10-20 21:46
169 查看
本文来自http://blog.csdn.net/runaying ,引用必须注明出处!
cocos2d-x 2.14默认项目注释
cocos2d-x默认项目注释1最常用的模板下载连接
//
// testAppDelegate.h
// test
//
// Created by ai on 13-10-19.
// Copyright __MyCompanyName__ 2013年. All rights reserved.
//
#ifndef _APP_DELEGATE_H_
#define _APP_DELEGATE_H_
#include "CCApplication.h"
/**
@brief The cocos2d Application.
使用 CCDirector实现私有继承的原因是隐藏一些界面细节
*/
class AppDelegate :privatecocos2d::CCApplication
{
public:
AppDelegate();
virtual ~AppDelegate();
/**
@brief
实现的CCDirector和CCScene这里初始化代码。
@return true
初始化成功 , app 继续.
@return false
初始化失败 , app 终止.
*/
virtualbool applicationDidFinishLaunching();
/**
@brief 函数被调用时,应用程序进入后台 //简要
@param
应用实例的指针 //参数
*/
virtualvoid applicationDidEnterBackground();
/**
@brief当应用程序调用该功能显示出来
@param
应用实例的指针
*/
virtualvoid applicationWillEnterForeground();
};
#endif // _APP_DELEGATE_H_
//
// testAppDelegate.cpp
// test
//
// Created by ai on 13-10-19.
// Copyright __MyCompanyName__ 2013年. All rights reserved.
//
#include "AppDelegate.h"
#include "cocos2d.h"
#include "SimpleAudioEngine.h"
#include "HelloWorldScene.h"
USING_NS_CC;
using namespace
CocosDenshion;
AppDelegate::AppDelegate()
{
}
AppDelegate::~AppDelegate()
{
}
//应用程序没有完成启动
boolAppDelegate::applicationDidFinishLaunching()
{
// initialize director
初始化导演
CCDirector *pDirector =CCDirector::sharedDirector();
pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());
// turn on display FPS
转到第一人称射击游戏
pDirector->setDisplayStats(true);
// set FPS.
默认的屏幕刷新间隔
pDirector->setAnimationInterval(1.0 /60);
//创建一个情景他是自动释放的对象
CCScene *pScene =HelloWorld::scene();
// run
pDirector->runWithScene(pScene);
return
true;
}
//这个函数将被调用时,应用程序是无效的。当来了一个电话,它被调用
voidAppDelegate::applicationDidEnterBackground()
{
CCDirector::sharedDirector()->stopAnimation();
SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
SimpleAudioEngine::sharedEngine()->pauseAllEffects();
}
// 当应用程序再次激活这个函数将被调用
voidAppDelegate::applicationWillEnterForeground()
{
CCDirector::sharedDirector()->startAnimation();
SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
SimpleAudioEngine::sharedEngine()->resumeAllEffects();
}
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
class HelloWorld :publiccocos2d::CCLayer
{
public:
//
初始化的方法返回一个 bool 值,而不是 cocos2d-iphone的' id '(一个对象指针)
virtualbool init();
// cpp中有没有' id ',所以我们建议返回类实例的指针
staticcocos2d::CCScene* scene();
//一个选择器的回调
void menuCloseCallback(CCObject* pSender);
// preprocessor macro for "static create()" constructor ( node() deprecated )
//预处理宏“静态 create()构造函数(节点()弃用)
CREATE_FUNC(HelloWorld);
};
#endif // __HELLOWORLD_SCENE_H__
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
using namespace
cocos2d;
using namespace
CocosDenshion;
CCScene* HelloWorld::scene()
{
//“场景”是一个自动释放的对象
CCScene *scene =CCScene::create();
// “层”是一个自动释放的对象
HelloWorld *layer =HelloWorld::create();
//加层作为一个子场景
scene->addChild(layer);
// return the scene
return scene;
}
//“初始化”,您需要初始化实例
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !CCLayer::init() )
{
return
false;
}
/////////////////////////////
// 2.使用一个图片添加一个菜单项,点击退出程序
//
你可以修改它。
//添加一个“关闭”图标,退出的进度。它是一个自动释放的对象
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);
/////////////////////////////
// 3. add your codes below...
//
添加一个标签显示的“Hello World”
//创建和初始化一个标签
CCLabelTTF* pLabel =CCLabelTTF::create("Hello
World","Thonburi",34);
//问导演窗口的大小
CCSize size =CCDirector::sharedDirector()->getWinSize();
//在屏幕的中心位置上的标签
pLabel->setPosition(ccp(size.width /2,
size.height -20) );
//把标签作为一个孩子到添加到这一层
this->addChild(pLabel,1);
//新增的“Hello World”图片“
CCSprite* pSprite =CCSprite::create("HelloWorld.png");
//精灵在屏幕中心的位置
pSprite->setPosition(ccp(size.width/2,
size.height/2) );
//作为一个孩子到这一层添加精灵
this->addChild(pSprite,0);
return
true;
}
voidHelloWorld::menuCloseCallback(CCObject* pSender)
{
CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
}
cocos2d-x默认项目注释Box2D.h
cocos2d-x默认项目注释2下载连接
//
// HelloWorldScene.h
// test2
//
// Created by ai on 13-10-19.
// Copyright __MyCompanyName__ 2013年. All rights reserved.
//
#ifndef __HELLO_WORLD_H__
#define __HELLO_WORLD_H__
// 当您导入此文件,导入所有的cocos2d类
#include "cocos2d.h"
#include "Box2D.h"
class PhysicsSprite :publiccocos2d::CCSprite
{
public:
PhysicsSprite();
void setPhysicsBody(b2Body * body);
virtualbool isDirty(void);
virtualcocos2d::CCAffineTransform nodeToParentTransform(void);
private:
b2Body* m_pBody; //强大的裁判
};
class HelloWorld :publiccocos2d::CCLayer
{
public:
~HelloWorld();
HelloWorld();
// 返回包含的HelloWorld作为唯一的孩子的场景
staticcocos2d::CCScene* scene();
void initPhysics();
//在一个给定的坐标中增加了一个新的sprite
void addNewSpriteAtPosition(cocos2d::CCPoint p);
virtualvoid draw();
virtualvoid ccTouchesEnded(cocos2d::CCSet*
touches,cocos2d::CCEvent* event);
void update(float dt);
private:
b2World* world;
cocos2d::CCTexture2D* m_pSpriteTexture;//弱引用
};
#endif // __HELLO_WORLD_H__
//
// HelloWorldScene.cpp
// test2
//
// Created by ai on 13-10-19.
// Copyright __MyCompanyName__ 2013年. All rights reserved.
//
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
using namespace cocos2d;
usingnamespace CocosDenshion;
#define PTM_RATIO 32
enum {
kTagParentNode =1,
};
PhysicsSprite::PhysicsSprite()
: m_pBody(NULL)
{
}
void PhysicsSprite::setPhysicsBody(b2Body * body)
{
m_pBody = body;
}
//这个方法只会被调用批处理精灵。
//返回YES,如果改变的物理值(角度,位置)
//如果返回NO,然后nodeToParentTransform将不会被调用。
bool PhysicsSprite::isDirty(void)
{
return
true;
}
// 根据花栗鼠的值返回变换矩阵
CCAffineTransform PhysicsSprite::nodeToParentTransform(void)
{
b2Vec2 pos = m_pBody->GetPosition();
float x = pos.x * PTM_RATIO;
float y = pos.y * PTM_RATIO;
if ( isIgnoreAnchorPointForPosition() ) {
x += m_obAnchorPointInPoints.x;
y += m_obAnchorPointInPoints.y;
}
//
制作矩阵
float radians = m_pBody->GetAngle();
float c = cosf(radians);
float s = sinf(radians);
if( ! m_obAnchorPointInPoints.equals(CCPointZero) ){
x += c*-m_obAnchorPointInPoints.x + -s*-m_obAnchorPointInPoints.y;
y += s*-m_obAnchorPointInPoints.x + c*-m_obAnchorPointInPoints.y;
}
// Rot,
翻译矩阵
m_sTransform = CCAffineTransformMake( c, s,
-s, c,
x, y );
return m_sTransform;
}
HelloWorld::HelloWorld()
{
setTouchEnabled(true );
setAccelerometerEnabled(true );
CCSize s = CCDirector::sharedDirector()->getWinSize();
//初始化物理
this->initPhysics();
CCSpriteBatchNode *parent = CCSpriteBatchNode::create("blocks.png",100);
m_pSpriteTexture = parent->getTexture();
addChild(parent,0, kTagParentNode);
addNewSpriteAtPosition(ccp(s.width/2, s.height/2));
CCLabelTTF *label = CCLabelTTF::create("Tap screen","Marker Felt",32);
addChild(label,0);
label->setColor(ccc3(0,0,255));
label->setPosition(ccp( s.width/2, s.height-50));
scheduleUpdate();
}
HelloWorld::~HelloWorld()
{
delete world;
world =NULL;
//删除 m_debugDraw;
}
void HelloWorld::initPhysics()
{
CCSize s = CCDirector::sharedDirector()->getWinSize();
b2Vec2 gravity;
gravity.Set(0.0f, -10.0f);
world =new b2World(gravity);
//我们想让机构睡觉?
world->SetAllowSleeping(true);
world->SetContinuousPhysics(true);
// m_debugDraw = new GLESDebugDraw( PTM_RATIO );
// world->SetDebugDraw(m_debugDraw);
uint32 flags =0;
flags += b2Draw::e_shapeBit;
// flags += b2Draw::e_jointBit;
// flags += b2Draw::e_aabbBit;
// flags += b2Draw::e_pairBit;
// flags += b2Draw::e_centerOfMassBit;
//m_debugDraw->SetFlags(flags);
//
定义地面主体。
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0,0);// bottom-left corner
// 调用车身工厂为地面箱体分配内存
// 从 pool中创建地面箱体(也从池中)。
// 主体也加入到世界各地。
b2Body* groundBody = world->CreateBody(&groundBodyDef);
//定义地面箱体框形。
b2EdgeShape groundBox;
// bottom
底部
groundBox.Set(b2Vec2(0,0), b2Vec2(s.width/PTM_RATIO,0));
groundBody->CreateFixture(&groundBox,0);
// top
顶部
groundBox.Set(b2Vec2(0,s.height/PTM_RATIO), b2Vec2(s.width/PTM_RATIO,s.height/PTM_RATIO));
groundBody->CreateFixture(&groundBox,0);
// left
左面
groundBox.Set(b2Vec2(0,s.height/PTM_RATIO), b2Vec2(0,0));
groundBody->CreateFixture(&groundBox,0);
// right
右面
groundBox.Set(b2Vec2(s.width/PTM_RATIO,s.height/PTM_RATIO), b2Vec2(s.width/PTM_RATIO,0));
groundBody->CreateFixture(&groundBox,0);
}
void HelloWorld::draw()
{
//
重要提示:
//这是只用于调试目的
//这里建议禁用它
CCLayer::draw();
ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position );
kmGLPushMatrix();
world->DrawDebugData();
kmGLPopMatrix();
}
void HelloWorld::addNewSpriteAtPosition(CCPoint p)
{
CCLOG("Add sprite %0.2f x %02.f",p.x,p.y);
CCNode* parent = getChildByTag(kTagParentNode);
//我们有一个64x64的精灵表有4种不同的32x32的图像。下面的代码是
//只是随机挑选其中一个图像
int idx = (CCRANDOM_0_1() >.5 ?0:1);
int idy = (CCRANDOM_0_1() >.5 ?0:1);
PhysicsSprite *sprite =new PhysicsSprite();
sprite->initWithTexture(m_pSpriteTexture, CCRectMake(32 * idx,32 * idy,32,32));
sprite->autorelease();
parent->addChild(sprite);
sprite->setPosition( CCPointMake( p.x, p.y) );
//定义的充满活力的身体。
//设置1米的方盒子在物理世界
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);
b2Body *body = world->CreateBody(&bodyDef);
//为我们充满活力的身体,定义另一个盒子形状。
b2PolygonShape dynamicBox;
dynamicBox.SetAsBox(.5f,.5f);//这些中点为1
m盒子
//定义动感的主体夹具。
b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicBox;
fixtureDef.density =1.0f;
fixtureDef.friction =0.3f;
body->CreateFixture(&fixtureDef);
sprite->setPhysicsBody(body);
}
void HelloWorld::update(float dt)
{
// /为了 Box2D的稳定这里建议使用一个固定的时间步长
// 模拟,在这里,我们使用的是一个可变的时间步长在这里。
// /你需要作出理智的选择,下面的URL是有用的
//http://gafferongames.com/game-physics/fix-your-timestep/
int velocityIterations =8;
int positionIterations =1;
// Instruct the world to perform a single step of simulation. It is
// generally best to keep the time step and iterations fixed.
// /指示世界模拟执行一个单一的步骤。这是
//一般最好保持固定时间步长,迭代。
// 提示,模拟现实世界执行一个单一的步骤,这里最好保持固定的时间步长,迭代
world->Step(dt, velocityIterations, positionIterations);
//在物理世界迭代的箱体
for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
{
if (b->GetUserData() !=NULL) {
//同步AtlasSprites,修改相应物体对应的位置和旋转角度
CCSprite* myActor = (CCSprite*)b->GetUserData();
myActor->setPosition( CCPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO) );
myActor->setRotation( -1 * CC_RADIANS_TO_DEGREES(b->GetAngle()) );
}
}
}
void HelloWorld::ccTouchesEnded(CCSet* touches, CCEvent* event)
{
//触摸位置添加一个新的机构/阿特拉斯精灵
CCSetIterator it;
CCTouch* touch;
for( it = touches->begin(); it != touches->end(); it++)
{
touch = (CCTouch*)(*it);
if(!touch)
break;
CCPoint location = touch->getLocationInView();
location = CCDirector::sharedDirector()->convertToGL(location);
addNewSpriteAtPosition( location );
}
}
CCScene* HelloWorld::scene()
{
// “场景”是一个自动释放的对象
CCScene *scene = CCScene::create();
//添加图层作为一个子的场景
CCLayer* layer =new HelloWorld();
scene->addChild(layer);
layer->release();
return scene;
}
cocos2d-x默认项目注释chipmunk.h
cocos2d-x默认项目注释3下载地址
//
// HelloWorldScene.h
// test3
//
// Created by ai on 13-10-19.
// Copyright __MyCompanyName__ 2013年. All rights reserved.
//
#ifndef __HELLOW_WORLD_H__
#define __HELLOW_WORLD_H__
#include "cocos2d.h"
// 包括 Chipmunk
头文件
#include "chipmunk.h"
class ChipmunkPhysicsSprite :publiccocos2d::CCSprite
{
public:
ChipmunkPhysicsSprite();
virtual ~ChipmunkPhysicsSprite();
void setPhysicsBody(cpBody* body);
virtualbool isDirty(void);
virtualcocos2d::CCAffineTransform nodeToParentTransform(void);
private:
cpBody* m_pBody; //强大的裁判
};
// HelloWorld Layer
class HelloWorld :publiccocos2d::CCLayer
{
public:
HelloWorld();
~HelloWorld();
bool init();
staticcocos2d::CCScene* scene();
CREATE_FUNC(HelloWorld);
void initPhysics();
void addNewSpriteAtPosition(cocos2d::CCPoint p);
void update(float dt);
virtualvoid ccTouchesEnded(cocos2d::CCSet*
touches,cocos2d::CCEvent* event);
virtualvoid didAccelerate(cocos2d::CCAcceleration*
pAccelerationValue);
private:
cocos2d::CCTexture2D* m_pSpriteTexture;// weak ref弱引用
cpSpace* m_pSpace;// strong ref 强大的裁判
cpShape* m_pWalls[4];
};
#endif // __HELLOW_WORLD_H__
//
// HelloWorldScene.cpp
// test3
//
// Created by ai on 13-10-19.
// Copyright __MyCompanyName__ 2013年. All rights reserved.
//
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
using namespace
cocos2d;
using namespace
CocosDenshion;
enum {
kTagParentNode =1,
};
//回调删除空间的形状
void removeShape(cpBody *body,cpShape *shape,void
*data )
{
cpShapeFree( shape );
}
ChipmunkPhysicsSprite::ChipmunkPhysicsSprite()
: m_pBody(NULL)
{
}
ChipmunkPhysicsSprite::~ChipmunkPhysicsSprite()
{
cpBodyEachShape(m_pBody,removeShape,NULL);
cpBodyFree(
m_pBody );
}
void ChipmunkPhysicsSprite::setPhysicsBody(cpBody * body)
{
m_pBody = body;
}
// 这个方法只会被批处理精灵调用。
// return YES 如果物理值改变(angles, position;角度位置)
// If you return NO,那么 nodeToParentTransform将不会被调用。
bool ChipmunkPhysicsSprite::isDirty(void)
{
return
true;
}
CCAffineTransform ChipmunkPhysicsSprite::nodeToParentTransform(void)
{
float x =m_pBody->p.x;
float y =m_pBody->p.y;
if (isIgnoreAnchorPointForPosition() ) {
x += m_obAnchorPointInPoints.x;
y += m_obAnchorPointInPoints.y;
}
//
制作矩阵
float c =m_pBody->rot.x;
float s =m_pBody->rot.y;
if( !m_obAnchorPointInPoints.equals(CCPointZero)
){
x += c*-m_obAnchorPointInPoints.x + -s*-m_obAnchorPointInPoints.y;
y += s*-m_obAnchorPointInPoints.x + c*-m_obAnchorPointInPoints.y;
}
// Rot,
翻译矩阵
m_sTransform =CCAffineTransformMake( c, s,
-s, c,
x, y );
returnm_sTransform;
}
HelloWorld::HelloWorld()
{
}
HelloWorld::~HelloWorld()
{
//
手动释放形状
for(int i=0;i<4;i++) {
cpShapeFree(m_pWalls[i] );
}
cpSpaceFree(
m_pSpace );
}
CCScene* HelloWorld::scene()
{
// 'scene' “场景”是一个自动释放的对象。
CCScene *scene =CCScene::create();
// 'layer' “层”是一个自动释放的对象。
HelloWorld *layer =HelloWorld::create();
//添加图层作为一个孩子的场景
scene->addChild(layer);
// return the scene
return scene;
}
bool HelloWorld::init()
{
if (!CCLayer::init())
{
return
false;
}
// enable events
启用事件
setTouchEnabled(true);
setAccelerometerEnabled(true);
CCSize s =CCDirector::sharedDirector()->getWinSize();
//标题
CCLabelTTF *label =CCLabelTTF::create("Multi
touch the screen","Marker Felt",36);
label->setPosition(ccp( s.width /2,
s.height -30));
this->addChild(label, -1);
// init physics
初始化物理
initPhysics();
#if 1
//使用分批节点。更快
CCSpriteBatchNode *parent =CCSpriteBatchNode::create("grossini_dance_atlas.png",100);
m_pSpriteTexture = parent->getTexture();
#else
// / /不使用批量节点。慢
m_pSpriteTexture = CCTextureCache::sharedTextureCache()->addImage("grossini_dance_atlas.png");
CCNode *parent = CCNode::node();
#endif
addChild(parent,0,kTagParentNode);
addNewSpriteAtPosition(ccp(200,200));
scheduleUpdate();
return
true;
}
voidHelloWorld::initPhysics()
{
CCSize s =CCDirector::sharedDirector()->getWinSize();
// init chipmunk
cpInitChipmunk();
m_pSpace =cpSpaceNew();
m_pSpace->gravity =cpv(0, -100);
// 形状
// 我们必须手动释放
//
// bottom
m_pWalls[0] =cpSegmentShapeNew(m_pSpace->staticBody,cpv(0,0),cpv(s.width,0),0.0f);
// top
m_pWalls[1] =cpSegmentShapeNew(m_pSpace->staticBody,cpv(0,s.height),cpv(s.width,s.height),0.0f);
// left
m_pWalls[2] =cpSegmentShapeNew(m_pSpace->staticBody,cpv(0,0),cpv(0,s.height),0.0f);
// right
m_pWalls[3] =cpSegmentShapeNew(m_pSpace->staticBody,cpv(s.width,0),cpv(s.width,s.height),0.0f);
for(int i=0;i<4;i++) {
m_pWalls[i]->e =1.0f;
m_pWalls[i]->u =1.0f;
cpSpaceAddStaticShape(m_pSpace,m_pWalls[i] );
}
}
voidHelloWorld::update(float delta)
{
// Should use a fixed size step based on the animation interval.
// 应使动画时间间隔在一个固定大小的步骤的基础上。
int steps =2;
float dt =CCDirector::sharedDirector()->getAnimationInterval()/(float)steps;
for(int i=0; i<steps; i++){
cpSpaceStep(m_pSpace, dt);
}
}
voidHelloWorld::addNewSpriteAtPosition(CCPoint pos)
{
int posx, posy;
CCNode *parent =getChildByTag(kTagParentNode);
posx =CCRANDOM_0_1() *200.0f;
posy =CCRANDOM_0_1() *200.0f;
posx = (posx %4) *85;
posy = (posy %3) *121;
ChipmunkPhysicsSprite *sprite =newChipmunkPhysicsSprite();
sprite->initWithTexture(m_pSpriteTexture,CCRectMake(posx, posy,85,121));
sprite->autorelease();
parent->addChild(sprite);
sprite->setPosition(pos);
int num =4;
cpVect verts[] = {
cpv(-24,-54),
cpv(-24,54),
cpv(24,54),
cpv(24,-54),
};
cpBody *body =cpBodyNew(1.0f,cpMomentForPoly(1.0f,
num, verts,cpvzero));
body->p =cpv(pos.x, pos.y);
cpSpaceAddBody(m_pSpace, body);
cpShape* shape =cpPolyShapeNew(body, num, verts,cpvzero);
shape->e =0.5f; shape->u =0.5f;
cpSpaceAddShape(m_pSpace, shape);
sprite->setPhysicsBody(body);
}
voidHelloWorld::ccTouchesEnded(CCSet* touches,CCEvent*
event)
{
//添加一个新的机构/阿特拉斯精灵触摸位置
CCSetIterator it;
CCTouch* touch;
for( it = touches->begin(); it != touches->end(); it++)
{
touch = (CCTouch*)(*it);
if(!touch)
break;
CCPoint location = touch->getLocationInView();
location =CCDirector::sharedDirector()->convertToGL(location);
addNewSpriteAtPosition( location );
}
}
voidHelloWorld::didAccelerate(CCAcceleration* pAccelerationValue)
{
staticfloat prevX=0, prevY=0;
#define kFilterFactor 0.05f
float accelX = (float) pAccelerationValue->x *kFilterFactor
+ (1-kFilterFactor)*prevX;
float accelY = (float) pAccelerationValue->y *kFilterFactor
+ (1-kFilterFactor)*prevY;
prevX = accelX;
prevY = accelY;
CCPoint v =ccp( accelX, accelY);
v =ccpMult(v,200);
m_pSpace->gravity =cpv(v.x, v.y);
}
cocos2d-x_js默认项目注释
cocos2d-x默认项目注释4
require("jsb.js");
try {
director = cc.Director.getInstance();
winSize = director.getWinSize();
centerPos = cc.p( winSize.width/2, winSize.height/2 );
//
// Main Menu
//
// 'MenuLayerController' class
是读者CocosBuilder实例
var MenuLayerController =function () {
};
// callback triggered by CCB Reader once the instance is created
// //触发回调实例由 CCB Reader
创建
MenuLayerController.prototype.onDidLoadFromCCB =function () {
// Spin the 'o' in the title
var o =this.titleLabel.getChildByTag(8);
var a_delay = cc.DelayTime.create(6);
var a_tint = cc.TintTo.create(0.5,0,255,0);
var a_rotate = cc.RotateBy.create(4,360);
var a_rep = cc.Repeat.create(a_rotate,1000);
var a_seq = cc.Sequence.create(a_delay, a_tint, a_delay.copy(), a_rep);
o.runAction(a_seq);
};
//用于菜单的回调,在编辑器中定义的
MenuLayerController.prototype.onPlay =function () {
director.replaceScene( cc.TransitionFade.create(1, game.getPlayScene()) );
};
MenuLayerController.prototype.onOptions =function () {
director.replaceScene( cc.TransitionFade.create(1, game.getOptionsScene()) );
};
MenuLayerController.prototype.onAbout =function () {
director.replaceScene( cc.TransitionZoomFlipY.create(1, game.getAboutScene()) );
};
var AboutLayerController =function() {}
AboutLayerController.prototype.onDidLoadFromCCB =function () {
var back = cc.MenuItemFont.create("Back",this.onBack,this);
back.setColor(cc.BLACK);
var menu = cc.Menu.create(back);
this.rootNode.addChild(menu);
menu.zOrder =100;
menu.alignItemsVertically();
menu.setPosition(winSize.width -50,50);
};
AboutLayerController.prototype.onBack =function () {
director.replaceScene( cc.TransitionFade.create(1, game.getMainMenuScene()));
};
var GameCreator =function() {
var self = {};
self.callbacks = {};
self.getPlayScene =function() {
var scene =new cc.Scene();
var layer =new cc.LayerGradient();
layer.init(cc.c4b(0,0,0,255),
cc.c4b(0,128,255,
255));
var lab ="Houston we have liftoff!";
var label = cc.LabelTTF.create(lab,"Arial",28);
layer.addChild(label,1);
label.setPosition( cc.p(winSize.width /2, winSize.height /2));
var back = cc.MenuItemFont.create("Back", self.callbacks.onBack, self.callbacks);
back.setColor( cc.BLACK );
var menu = cc.Menu.create( back );
layer.addChild( menu );
menu.alignItemsVertically();
menu.setPosition( cc.p( winSize.width -50,50) );
scene.addChild(layer);
return scene;
};
self.getMainMenuScene =function() {
return cc.BuilderReader.loadAsScene("MainMenu.ccbi");
};
self.getOptionsScene =function() {
var l = cc.LayerGradient.create();
l.init(cc.c4b(0,0,0,255),
cc.c4b(255,255,255,
255));
var scene = cc.Scene.create();
var label1 = cc.LabelBMFont.create("MUSIC ON","konqa32.fnt" );
var item1 = cc.MenuItemLabel.create(label1);
var label2 = cc.LabelBMFont.create("MUSIC OFF","konqa32.fnt"
);
var item2 = cc.MenuItemLabel.create(label2);
var toggle = cc.MenuItemToggle.create( item1, item2 );
this.onMusicToggle =function( sender ) {
cc.log("OptionsScene onMusicToggle...");
};
toggle.setCallback(this.onMusicToggle,this);
var back = cc.MenuItemFont.create("Back", self.callbacks.onBack, self.callbacks);
var menu = cc.Menu.create( toggle, back );
l.addChild( menu );
menu.alignItemsVertically();
menu.setPosition( centerPos );
scene.addChild(l);
return scene;
};
self.getAboutScene =function() {
var scene = cc.Scene.create();
var l = cc.Layer.create();
var about = cc.BuilderReader.load("About.ccbi", l);
l.addChild( about )
scene.addChild( l );
return scene;
};
//手动回调
self.callbacks.onBack =function( sender) {
director.replaceScene( cc.TransitionFlipX.create(1, self.getMainMenuScene()) );
};
return self;
};
var game = GameCreator();
__jsc__.garbageCollect();
// LOADING PLAY SCENE UNTILL CCBREADER IS FIXED
// LOADING PLAY场景直到CCBREADER是固定的
director.runWithScene(game.getPlayScene());
}catch(e) {log(e);}
cocos2d-x 2.14默认项目注释
cocos2d-x默认项目注释1最常用的模板下载连接
//
// testAppDelegate.h
// test
//
// Created by ai on 13-10-19.
// Copyright __MyCompanyName__ 2013年. All rights reserved.
//
#ifndef _APP_DELEGATE_H_
#define _APP_DELEGATE_H_
#include "CCApplication.h"
/**
@brief The cocos2d Application.
使用 CCDirector实现私有继承的原因是隐藏一些界面细节
*/
class AppDelegate :privatecocos2d::CCApplication
{
public:
AppDelegate();
virtual ~AppDelegate();
/**
@brief
实现的CCDirector和CCScene这里初始化代码。
@return true
初始化成功 , app 继续.
@return false
初始化失败 , app 终止.
*/
virtualbool applicationDidFinishLaunching();
/**
@brief 函数被调用时,应用程序进入后台 //简要
@param
应用实例的指针 //参数
*/
virtualvoid applicationDidEnterBackground();
/**
@brief当应用程序调用该功能显示出来
@param
应用实例的指针
*/
virtualvoid applicationWillEnterForeground();
};
#endif // _APP_DELEGATE_H_
//
// testAppDelegate.cpp
// test
//
// Created by ai on 13-10-19.
// Copyright __MyCompanyName__ 2013年. All rights reserved.
//
#include "AppDelegate.h"
#include "cocos2d.h"
#include "SimpleAudioEngine.h"
#include "HelloWorldScene.h"
USING_NS_CC;
using namespace
CocosDenshion;
AppDelegate::AppDelegate()
{
}
AppDelegate::~AppDelegate()
{
}
//应用程序没有完成启动
boolAppDelegate::applicationDidFinishLaunching()
{
// initialize director
初始化导演
CCDirector *pDirector =CCDirector::sharedDirector();
pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());
// turn on display FPS
转到第一人称射击游戏
pDirector->setDisplayStats(true);
// set FPS.
默认的屏幕刷新间隔
pDirector->setAnimationInterval(1.0 /60);
//创建一个情景他是自动释放的对象
CCScene *pScene =HelloWorld::scene();
// run
pDirector->runWithScene(pScene);
return
true;
}
//这个函数将被调用时,应用程序是无效的。当来了一个电话,它被调用
voidAppDelegate::applicationDidEnterBackground()
{
CCDirector::sharedDirector()->stopAnimation();
SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
SimpleAudioEngine::sharedEngine()->pauseAllEffects();
}
// 当应用程序再次激活这个函数将被调用
voidAppDelegate::applicationWillEnterForeground()
{
CCDirector::sharedDirector()->startAnimation();
SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
SimpleAudioEngine::sharedEngine()->resumeAllEffects();
}
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
class HelloWorld :publiccocos2d::CCLayer
{
public:
//
初始化的方法返回一个 bool 值,而不是 cocos2d-iphone的' id '(一个对象指针)
virtualbool init();
// cpp中有没有' id ',所以我们建议返回类实例的指针
staticcocos2d::CCScene* scene();
//一个选择器的回调
void menuCloseCallback(CCObject* pSender);
// preprocessor macro for "static create()" constructor ( node() deprecated )
//预处理宏“静态 create()构造函数(节点()弃用)
CREATE_FUNC(HelloWorld);
};
#endif // __HELLOWORLD_SCENE_H__
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
using namespace
cocos2d;
using namespace
CocosDenshion;
CCScene* HelloWorld::scene()
{
//“场景”是一个自动释放的对象
CCScene *scene =CCScene::create();
// “层”是一个自动释放的对象
HelloWorld *layer =HelloWorld::create();
//加层作为一个子场景
scene->addChild(layer);
// return the scene
return scene;
}
//“初始化”,您需要初始化实例
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !CCLayer::init() )
{
return
false;
}
/////////////////////////////
// 2.使用一个图片添加一个菜单项,点击退出程序
//
你可以修改它。
//添加一个“关闭”图标,退出的进度。它是一个自动释放的对象
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);
/////////////////////////////
// 3. add your codes below...
//
添加一个标签显示的“Hello World”
//创建和初始化一个标签
CCLabelTTF* pLabel =CCLabelTTF::create("Hello
World","Thonburi",34);
//问导演窗口的大小
CCSize size =CCDirector::sharedDirector()->getWinSize();
//在屏幕的中心位置上的标签
pLabel->setPosition(ccp(size.width /2,
size.height -20) );
//把标签作为一个孩子到添加到这一层
this->addChild(pLabel,1);
//新增的“Hello World”图片“
CCSprite* pSprite =CCSprite::create("HelloWorld.png");
//精灵在屏幕中心的位置
pSprite->setPosition(ccp(size.width/2,
size.height/2) );
//作为一个孩子到这一层添加精灵
this->addChild(pSprite,0);
return
true;
}
voidHelloWorld::menuCloseCallback(CCObject* pSender)
{
CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
}
cocos2d-x默认项目注释Box2D.h
cocos2d-x默认项目注释2下载连接
//
// HelloWorldScene.h
// test2
//
// Created by ai on 13-10-19.
// Copyright __MyCompanyName__ 2013年. All rights reserved.
//
#ifndef __HELLO_WORLD_H__
#define __HELLO_WORLD_H__
// 当您导入此文件,导入所有的cocos2d类
#include "cocos2d.h"
#include "Box2D.h"
class PhysicsSprite :publiccocos2d::CCSprite
{
public:
PhysicsSprite();
void setPhysicsBody(b2Body * body);
virtualbool isDirty(void);
virtualcocos2d::CCAffineTransform nodeToParentTransform(void);
private:
b2Body* m_pBody; //强大的裁判
};
class HelloWorld :publiccocos2d::CCLayer
{
public:
~HelloWorld();
HelloWorld();
// 返回包含的HelloWorld作为唯一的孩子的场景
staticcocos2d::CCScene* scene();
void initPhysics();
//在一个给定的坐标中增加了一个新的sprite
void addNewSpriteAtPosition(cocos2d::CCPoint p);
virtualvoid draw();
virtualvoid ccTouchesEnded(cocos2d::CCSet*
touches,cocos2d::CCEvent* event);
void update(float dt);
private:
b2World* world;
cocos2d::CCTexture2D* m_pSpriteTexture;//弱引用
};
#endif // __HELLO_WORLD_H__
//
// HelloWorldScene.cpp
// test2
//
// Created by ai on 13-10-19.
// Copyright __MyCompanyName__ 2013年. All rights reserved.
//
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
using namespace cocos2d;
usingnamespace CocosDenshion;
#define PTM_RATIO 32
enum {
kTagParentNode =1,
};
PhysicsSprite::PhysicsSprite()
: m_pBody(NULL)
{
}
void PhysicsSprite::setPhysicsBody(b2Body * body)
{
m_pBody = body;
}
//这个方法只会被调用批处理精灵。
//返回YES,如果改变的物理值(角度,位置)
//如果返回NO,然后nodeToParentTransform将不会被调用。
bool PhysicsSprite::isDirty(void)
{
return
true;
}
// 根据花栗鼠的值返回变换矩阵
CCAffineTransform PhysicsSprite::nodeToParentTransform(void)
{
b2Vec2 pos = m_pBody->GetPosition();
float x = pos.x * PTM_RATIO;
float y = pos.y * PTM_RATIO;
if ( isIgnoreAnchorPointForPosition() ) {
x += m_obAnchorPointInPoints.x;
y += m_obAnchorPointInPoints.y;
}
//
制作矩阵
float radians = m_pBody->GetAngle();
float c = cosf(radians);
float s = sinf(radians);
if( ! m_obAnchorPointInPoints.equals(CCPointZero) ){
x += c*-m_obAnchorPointInPoints.x + -s*-m_obAnchorPointInPoints.y;
y += s*-m_obAnchorPointInPoints.x + c*-m_obAnchorPointInPoints.y;
}
// Rot,
翻译矩阵
m_sTransform = CCAffineTransformMake( c, s,
-s, c,
x, y );
return m_sTransform;
}
HelloWorld::HelloWorld()
{
setTouchEnabled(true );
setAccelerometerEnabled(true );
CCSize s = CCDirector::sharedDirector()->getWinSize();
//初始化物理
this->initPhysics();
CCSpriteBatchNode *parent = CCSpriteBatchNode::create("blocks.png",100);
m_pSpriteTexture = parent->getTexture();
addChild(parent,0, kTagParentNode);
addNewSpriteAtPosition(ccp(s.width/2, s.height/2));
CCLabelTTF *label = CCLabelTTF::create("Tap screen","Marker Felt",32);
addChild(label,0);
label->setColor(ccc3(0,0,255));
label->setPosition(ccp( s.width/2, s.height-50));
scheduleUpdate();
}
HelloWorld::~HelloWorld()
{
delete world;
world =NULL;
//删除 m_debugDraw;
}
void HelloWorld::initPhysics()
{
CCSize s = CCDirector::sharedDirector()->getWinSize();
b2Vec2 gravity;
gravity.Set(0.0f, -10.0f);
world =new b2World(gravity);
//我们想让机构睡觉?
world->SetAllowSleeping(true);
world->SetContinuousPhysics(true);
// m_debugDraw = new GLESDebugDraw( PTM_RATIO );
// world->SetDebugDraw(m_debugDraw);
uint32 flags =0;
flags += b2Draw::e_shapeBit;
// flags += b2Draw::e_jointBit;
// flags += b2Draw::e_aabbBit;
// flags += b2Draw::e_pairBit;
// flags += b2Draw::e_centerOfMassBit;
//m_debugDraw->SetFlags(flags);
//
定义地面主体。
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0,0);// bottom-left corner
// 调用车身工厂为地面箱体分配内存
// 从 pool中创建地面箱体(也从池中)。
// 主体也加入到世界各地。
b2Body* groundBody = world->CreateBody(&groundBodyDef);
//定义地面箱体框形。
b2EdgeShape groundBox;
// bottom
底部
groundBox.Set(b2Vec2(0,0), b2Vec2(s.width/PTM_RATIO,0));
groundBody->CreateFixture(&groundBox,0);
// top
顶部
groundBox.Set(b2Vec2(0,s.height/PTM_RATIO), b2Vec2(s.width/PTM_RATIO,s.height/PTM_RATIO));
groundBody->CreateFixture(&groundBox,0);
// left
左面
groundBox.Set(b2Vec2(0,s.height/PTM_RATIO), b2Vec2(0,0));
groundBody->CreateFixture(&groundBox,0);
// right
右面
groundBox.Set(b2Vec2(s.width/PTM_RATIO,s.height/PTM_RATIO), b2Vec2(s.width/PTM_RATIO,0));
groundBody->CreateFixture(&groundBox,0);
}
void HelloWorld::draw()
{
//
重要提示:
//这是只用于调试目的
//这里建议禁用它
CCLayer::draw();
ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position );
kmGLPushMatrix();
world->DrawDebugData();
kmGLPopMatrix();
}
void HelloWorld::addNewSpriteAtPosition(CCPoint p)
{
CCLOG("Add sprite %0.2f x %02.f",p.x,p.y);
CCNode* parent = getChildByTag(kTagParentNode);
//我们有一个64x64的精灵表有4种不同的32x32的图像。下面的代码是
//只是随机挑选其中一个图像
int idx = (CCRANDOM_0_1() >.5 ?0:1);
int idy = (CCRANDOM_0_1() >.5 ?0:1);
PhysicsSprite *sprite =new PhysicsSprite();
sprite->initWithTexture(m_pSpriteTexture, CCRectMake(32 * idx,32 * idy,32,32));
sprite->autorelease();
parent->addChild(sprite);
sprite->setPosition( CCPointMake( p.x, p.y) );
//定义的充满活力的身体。
//设置1米的方盒子在物理世界
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);
b2Body *body = world->CreateBody(&bodyDef);
//为我们充满活力的身体,定义另一个盒子形状。
b2PolygonShape dynamicBox;
dynamicBox.SetAsBox(.5f,.5f);//这些中点为1
m盒子
//定义动感的主体夹具。
b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicBox;
fixtureDef.density =1.0f;
fixtureDef.friction =0.3f;
body->CreateFixture(&fixtureDef);
sprite->setPhysicsBody(body);
}
void HelloWorld::update(float dt)
{
// /为了 Box2D的稳定这里建议使用一个固定的时间步长
// 模拟,在这里,我们使用的是一个可变的时间步长在这里。
// /你需要作出理智的选择,下面的URL是有用的
//http://gafferongames.com/game-physics/fix-your-timestep/
int velocityIterations =8;
int positionIterations =1;
// Instruct the world to perform a single step of simulation. It is
// generally best to keep the time step and iterations fixed.
// /指示世界模拟执行一个单一的步骤。这是
//一般最好保持固定时间步长,迭代。
// 提示,模拟现实世界执行一个单一的步骤,这里最好保持固定的时间步长,迭代
world->Step(dt, velocityIterations, positionIterations);
//在物理世界迭代的箱体
for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
{
if (b->GetUserData() !=NULL) {
//同步AtlasSprites,修改相应物体对应的位置和旋转角度
CCSprite* myActor = (CCSprite*)b->GetUserData();
myActor->setPosition( CCPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO) );
myActor->setRotation( -1 * CC_RADIANS_TO_DEGREES(b->GetAngle()) );
}
}
}
void HelloWorld::ccTouchesEnded(CCSet* touches, CCEvent* event)
{
//触摸位置添加一个新的机构/阿特拉斯精灵
CCSetIterator it;
CCTouch* touch;
for( it = touches->begin(); it != touches->end(); it++)
{
touch = (CCTouch*)(*it);
if(!touch)
break;
CCPoint location = touch->getLocationInView();
location = CCDirector::sharedDirector()->convertToGL(location);
addNewSpriteAtPosition( location );
}
}
CCScene* HelloWorld::scene()
{
// “场景”是一个自动释放的对象
CCScene *scene = CCScene::create();
//添加图层作为一个子的场景
CCLayer* layer =new HelloWorld();
scene->addChild(layer);
layer->release();
return scene;
}
cocos2d-x默认项目注释chipmunk.h
cocos2d-x默认项目注释3下载地址
//
// HelloWorldScene.h
// test3
//
// Created by ai on 13-10-19.
// Copyright __MyCompanyName__ 2013年. All rights reserved.
//
#ifndef __HELLOW_WORLD_H__
#define __HELLOW_WORLD_H__
#include "cocos2d.h"
// 包括 Chipmunk
头文件
#include "chipmunk.h"
class ChipmunkPhysicsSprite :publiccocos2d::CCSprite
{
public:
ChipmunkPhysicsSprite();
virtual ~ChipmunkPhysicsSprite();
void setPhysicsBody(cpBody* body);
virtualbool isDirty(void);
virtualcocos2d::CCAffineTransform nodeToParentTransform(void);
private:
cpBody* m_pBody; //强大的裁判
};
// HelloWorld Layer
class HelloWorld :publiccocos2d::CCLayer
{
public:
HelloWorld();
~HelloWorld();
bool init();
staticcocos2d::CCScene* scene();
CREATE_FUNC(HelloWorld);
void initPhysics();
void addNewSpriteAtPosition(cocos2d::CCPoint p);
void update(float dt);
virtualvoid ccTouchesEnded(cocos2d::CCSet*
touches,cocos2d::CCEvent* event);
virtualvoid didAccelerate(cocos2d::CCAcceleration*
pAccelerationValue);
private:
cocos2d::CCTexture2D* m_pSpriteTexture;// weak ref弱引用
cpSpace* m_pSpace;// strong ref 强大的裁判
cpShape* m_pWalls[4];
};
#endif // __HELLOW_WORLD_H__
//
// HelloWorldScene.cpp
// test3
//
// Created by ai on 13-10-19.
// Copyright __MyCompanyName__ 2013年. All rights reserved.
//
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
using namespace
cocos2d;
using namespace
CocosDenshion;
enum {
kTagParentNode =1,
};
//回调删除空间的形状
void removeShape(cpBody *body,cpShape *shape,void
*data )
{
cpShapeFree( shape );
}
ChipmunkPhysicsSprite::ChipmunkPhysicsSprite()
: m_pBody(NULL)
{
}
ChipmunkPhysicsSprite::~ChipmunkPhysicsSprite()
{
cpBodyEachShape(m_pBody,removeShape,NULL);
cpBodyFree(
m_pBody );
}
void ChipmunkPhysicsSprite::setPhysicsBody(cpBody * body)
{
m_pBody = body;
}
// 这个方法只会被批处理精灵调用。
// return YES 如果物理值改变(angles, position;角度位置)
// If you return NO,那么 nodeToParentTransform将不会被调用。
bool ChipmunkPhysicsSprite::isDirty(void)
{
return
true;
}
CCAffineTransform ChipmunkPhysicsSprite::nodeToParentTransform(void)
{
float x =m_pBody->p.x;
float y =m_pBody->p.y;
if (isIgnoreAnchorPointForPosition() ) {
x += m_obAnchorPointInPoints.x;
y += m_obAnchorPointInPoints.y;
}
//
制作矩阵
float c =m_pBody->rot.x;
float s =m_pBody->rot.y;
if( !m_obAnchorPointInPoints.equals(CCPointZero)
){
x += c*-m_obAnchorPointInPoints.x + -s*-m_obAnchorPointInPoints.y;
y += s*-m_obAnchorPointInPoints.x + c*-m_obAnchorPointInPoints.y;
}
// Rot,
翻译矩阵
m_sTransform =CCAffineTransformMake( c, s,
-s, c,
x, y );
returnm_sTransform;
}
HelloWorld::HelloWorld()
{
}
HelloWorld::~HelloWorld()
{
//
手动释放形状
for(int i=0;i<4;i++) {
cpShapeFree(m_pWalls[i] );
}
cpSpaceFree(
m_pSpace );
}
CCScene* HelloWorld::scene()
{
// 'scene' “场景”是一个自动释放的对象。
CCScene *scene =CCScene::create();
// 'layer' “层”是一个自动释放的对象。
HelloWorld *layer =HelloWorld::create();
//添加图层作为一个孩子的场景
scene->addChild(layer);
// return the scene
return scene;
}
bool HelloWorld::init()
{
if (!CCLayer::init())
{
return
false;
}
// enable events
启用事件
setTouchEnabled(true);
setAccelerometerEnabled(true);
CCSize s =CCDirector::sharedDirector()->getWinSize();
//标题
CCLabelTTF *label =CCLabelTTF::create("Multi
touch the screen","Marker Felt",36);
label->setPosition(ccp( s.width /2,
s.height -30));
this->addChild(label, -1);
// init physics
初始化物理
initPhysics();
#if 1
//使用分批节点。更快
CCSpriteBatchNode *parent =CCSpriteBatchNode::create("grossini_dance_atlas.png",100);
m_pSpriteTexture = parent->getTexture();
#else
// / /不使用批量节点。慢
m_pSpriteTexture = CCTextureCache::sharedTextureCache()->addImage("grossini_dance_atlas.png");
CCNode *parent = CCNode::node();
#endif
addChild(parent,0,kTagParentNode);
addNewSpriteAtPosition(ccp(200,200));
scheduleUpdate();
return
true;
}
voidHelloWorld::initPhysics()
{
CCSize s =CCDirector::sharedDirector()->getWinSize();
// init chipmunk
cpInitChipmunk();
m_pSpace =cpSpaceNew();
m_pSpace->gravity =cpv(0, -100);
// 形状
// 我们必须手动释放
//
// bottom
m_pWalls[0] =cpSegmentShapeNew(m_pSpace->staticBody,cpv(0,0),cpv(s.width,0),0.0f);
// top
m_pWalls[1] =cpSegmentShapeNew(m_pSpace->staticBody,cpv(0,s.height),cpv(s.width,s.height),0.0f);
// left
m_pWalls[2] =cpSegmentShapeNew(m_pSpace->staticBody,cpv(0,0),cpv(0,s.height),0.0f);
// right
m_pWalls[3] =cpSegmentShapeNew(m_pSpace->staticBody,cpv(s.width,0),cpv(s.width,s.height),0.0f);
for(int i=0;i<4;i++) {
m_pWalls[i]->e =1.0f;
m_pWalls[i]->u =1.0f;
cpSpaceAddStaticShape(m_pSpace,m_pWalls[i] );
}
}
voidHelloWorld::update(float delta)
{
// Should use a fixed size step based on the animation interval.
// 应使动画时间间隔在一个固定大小的步骤的基础上。
int steps =2;
float dt =CCDirector::sharedDirector()->getAnimationInterval()/(float)steps;
for(int i=0; i<steps; i++){
cpSpaceStep(m_pSpace, dt);
}
}
voidHelloWorld::addNewSpriteAtPosition(CCPoint pos)
{
int posx, posy;
CCNode *parent =getChildByTag(kTagParentNode);
posx =CCRANDOM_0_1() *200.0f;
posy =CCRANDOM_0_1() *200.0f;
posx = (posx %4) *85;
posy = (posy %3) *121;
ChipmunkPhysicsSprite *sprite =newChipmunkPhysicsSprite();
sprite->initWithTexture(m_pSpriteTexture,CCRectMake(posx, posy,85,121));
sprite->autorelease();
parent->addChild(sprite);
sprite->setPosition(pos);
int num =4;
cpVect verts[] = {
cpv(-24,-54),
cpv(-24,54),
cpv(24,54),
cpv(24,-54),
};
cpBody *body =cpBodyNew(1.0f,cpMomentForPoly(1.0f,
num, verts,cpvzero));
body->p =cpv(pos.x, pos.y);
cpSpaceAddBody(m_pSpace, body);
cpShape* shape =cpPolyShapeNew(body, num, verts,cpvzero);
shape->e =0.5f; shape->u =0.5f;
cpSpaceAddShape(m_pSpace, shape);
sprite->setPhysicsBody(body);
}
voidHelloWorld::ccTouchesEnded(CCSet* touches,CCEvent*
event)
{
//添加一个新的机构/阿特拉斯精灵触摸位置
CCSetIterator it;
CCTouch* touch;
for( it = touches->begin(); it != touches->end(); it++)
{
touch = (CCTouch*)(*it);
if(!touch)
break;
CCPoint location = touch->getLocationInView();
location =CCDirector::sharedDirector()->convertToGL(location);
addNewSpriteAtPosition( location );
}
}
voidHelloWorld::didAccelerate(CCAcceleration* pAccelerationValue)
{
staticfloat prevX=0, prevY=0;
#define kFilterFactor 0.05f
float accelX = (float) pAccelerationValue->x *kFilterFactor
+ (1-kFilterFactor)*prevX;
float accelY = (float) pAccelerationValue->y *kFilterFactor
+ (1-kFilterFactor)*prevY;
prevX = accelX;
prevY = accelY;
CCPoint v =ccp( accelX, accelY);
v =ccpMult(v,200);
m_pSpace->gravity =cpv(v.x, v.y);
}
cocos2d-x_js默认项目注释
cocos2d-x默认项目注释4
require("jsb.js");
try {
director = cc.Director.getInstance();
winSize = director.getWinSize();
centerPos = cc.p( winSize.width/2, winSize.height/2 );
//
// Main Menu
//
// 'MenuLayerController' class
是读者CocosBuilder实例
var MenuLayerController =function () {
};
// callback triggered by CCB Reader once the instance is created
// //触发回调实例由 CCB Reader
创建
MenuLayerController.prototype.onDidLoadFromCCB =function () {
// Spin the 'o' in the title
var o =this.titleLabel.getChildByTag(8);
var a_delay = cc.DelayTime.create(6);
var a_tint = cc.TintTo.create(0.5,0,255,0);
var a_rotate = cc.RotateBy.create(4,360);
var a_rep = cc.Repeat.create(a_rotate,1000);
var a_seq = cc.Sequence.create(a_delay, a_tint, a_delay.copy(), a_rep);
o.runAction(a_seq);
};
//用于菜单的回调,在编辑器中定义的
MenuLayerController.prototype.onPlay =function () {
director.replaceScene( cc.TransitionFade.create(1, game.getPlayScene()) );
};
MenuLayerController.prototype.onOptions =function () {
director.replaceScene( cc.TransitionFade.create(1, game.getOptionsScene()) );
};
MenuLayerController.prototype.onAbout =function () {
director.replaceScene( cc.TransitionZoomFlipY.create(1, game.getAboutScene()) );
};
var AboutLayerController =function() {}
AboutLayerController.prototype.onDidLoadFromCCB =function () {
var back = cc.MenuItemFont.create("Back",this.onBack,this);
back.setColor(cc.BLACK);
var menu = cc.Menu.create(back);
this.rootNode.addChild(menu);
menu.zOrder =100;
menu.alignItemsVertically();
menu.setPosition(winSize.width -50,50);
};
AboutLayerController.prototype.onBack =function () {
director.replaceScene( cc.TransitionFade.create(1, game.getMainMenuScene()));
};
var GameCreator =function() {
var self = {};
self.callbacks = {};
self.getPlayScene =function() {
var scene =new cc.Scene();
var layer =new cc.LayerGradient();
layer.init(cc.c4b(0,0,0,255),
cc.c4b(0,128,255,
255));
var lab ="Houston we have liftoff!";
var label = cc.LabelTTF.create(lab,"Arial",28);
layer.addChild(label,1);
label.setPosition( cc.p(winSize.width /2, winSize.height /2));
var back = cc.MenuItemFont.create("Back", self.callbacks.onBack, self.callbacks);
back.setColor( cc.BLACK );
var menu = cc.Menu.create( back );
layer.addChild( menu );
menu.alignItemsVertically();
menu.setPosition( cc.p( winSize.width -50,50) );
scene.addChild(layer);
return scene;
};
self.getMainMenuScene =function() {
return cc.BuilderReader.loadAsScene("MainMenu.ccbi");
};
self.getOptionsScene =function() {
var l = cc.LayerGradient.create();
l.init(cc.c4b(0,0,0,255),
cc.c4b(255,255,255,
255));
var scene = cc.Scene.create();
var label1 = cc.LabelBMFont.create("MUSIC ON","konqa32.fnt" );
var item1 = cc.MenuItemLabel.create(label1);
var label2 = cc.LabelBMFont.create("MUSIC OFF","konqa32.fnt"
);
var item2 = cc.MenuItemLabel.create(label2);
var toggle = cc.MenuItemToggle.create( item1, item2 );
this.onMusicToggle =function( sender ) {
cc.log("OptionsScene onMusicToggle...");
};
toggle.setCallback(this.onMusicToggle,this);
var back = cc.MenuItemFont.create("Back", self.callbacks.onBack, self.callbacks);
var menu = cc.Menu.create( toggle, back );
l.addChild( menu );
menu.alignItemsVertically();
menu.setPosition( centerPos );
scene.addChild(l);
return scene;
};
self.getAboutScene =function() {
var scene = cc.Scene.create();
var l = cc.Layer.create();
var about = cc.BuilderReader.load("About.ccbi", l);
l.addChild( about )
scene.addChild( l );
return scene;
};
//手动回调
self.callbacks.onBack =function( sender) {
director.replaceScene( cc.TransitionFlipX.create(1, self.getMainMenuScene()) );
};
return self;
};
var game = GameCreator();
__jsc__.garbageCollect();
// LOADING PLAY SCENE UNTILL CCBREADER IS FIXED
// LOADING PLAY场景直到CCBREADER是固定的
director.runWithScene(game.getPlayScene());
}catch(e) {log(e);}
相关文章推荐
- Mac 上编译cocos2d-x 2.14 android项目个人记录
- cocos2d-x 2.14 win32 项目移植到android
- 怎样使项目中的cocos2d默认模板支持ARC内存管理
- Windows Azure 项目笔记#2 - 项目引用与默认页面
- Cocos2d-x v3.0正式版尝鲜体验【1】 环境搭建和新建项目
- 【加快cocos2d-x编译速度】cocos2d-x编译项目时避免拷贝文件夹和库
- rhel7 升级内核,保证grub2启动时为默认项目
- web工程设置项目的默认访问路径和登录拦截
- cocos2d-x 2.2.1 在WINDOWS中如何创建项目
- ASP.NET 之 CheckBoxList在实际项目中的应用——高级查询、数据库读出默认选中
- cocos2d-x项目与vs2013编译
- Cocos2d-x开发教程 第一节 开发环境安装与示例项目创建
- 【C语言】注释转换项目实现
- Cocos2d-x 3.2 大富翁游戏项目开发-第六部分 地图设计
- Cocos2d-x 3.0 beta 中加入附加项目,解决无法打开包括文件:“extensions/ExtensionMacros.h”
- Macbook终端创建cocos2d-x项目
- IIS里面是空的,没有"默认网站",右侧提示“此视图中没有可显示的项目”
- cocos2d-x项目过程记录(纹理和内存优化方面)
- cocos2d-x SpaceFighting类似打飞机游戏小项目