Cocos2d-x-3.6学习(三)---- TestCpp学习
来源:互联网 发布:最小生成树算法 编辑:程序博客网 时间:2024/06/15 20:06
一、C++
1.注释
/** * @class 类名 * @brief 类、函数功能简要说明 * @since 版本 * @param 参数及说明 * @return 返回值说明 * @note 使用说明 */2.C++ 11
(1)auto自动类型推导
auto a; // 错误,auto是通过初始化表达式进行类型推导,如果没有初始化表达式,就无法确定a的类型 auto i = 1; //intauto d = 1.0; //doubleauto str = "Hello World"; //stringauto ch = 'A'; //charauto func = less<int>(); vector<int> iv; auto ite = iv.begin(); auto p = new foo() // 对自定义类型进行类型推导
vector迭代器
vector<int> vec; vector<int>::iterator itr = vec.iterator(); //使用autovector<int> vec; auto itr = vec.iterator();
(2)序列for循环
在C++中for循环可以使用类似java的简化的for循环,可以用于遍历数组,容器,string以及由begin和end函数定义的序列(即有Iterator),示例代码如下:map<string, int> m{{"a", 1}, {"b", 2}, {"c", 3}}; for (auto p : m){ cout<<p.first<<" : "<<p.second<<endl; }
(3)成员变量初始化
与Java和C#中的用法一样,可以对成员变量进行就地初始化。示例代码如下:class CPerson{ private: int m_nAge = 10; string m_strName = "Mike";};
(4)显式虚函数重载
在引入C++ 11之前,基类和派生类中的虚函数很容易产生错误使用的情况。比如:a、基类添加了一个虚函数,但该虚函数与派生类中的某个已有普通函数相同。
b、派生类添加了一个普通函数,但该函数与基类中的某个已有虚函数相同。
为了避免这些情况,在C++ 11中可以使用override来显式地表明需要进行虚函数重载。比如:
class Base { virtual void some_func(float);};class Derived : public Base{ virtual void some_func(int) override; // 将产生编译错误 virtual void some_func(float) override; // 正确};
二、3.x与2.x
1.新的callback
// new callbacks based on C++11#define CC_CALLBACK_0(__selector__,__target__, ...) std::bind(&__selector__,__target__, ##__VA_ARGS__)#define CC_CALLBACK_1(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, ##__VA_ARGS__)#define CC_CALLBACK_2(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, std::placeholders::_2, ##__VA_ARGS__)#define CC_CALLBACK_3(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, ##__VA_ARGS__)
2.去掉所有CC前缀
3.getInstance()单例模式
在v3.0之前,单例类的构造方式是CocosClass::sharedCocosClass(),比如:TextureCache::sharedTextureCache()。
/** * Returns a shared instance of the director. */ static Director* getInstance(); /** * @deprecated Use getInstance() instead. */ CC_DEPRECATED_ATTRIBUTE static Director* sharedDirector() { return Director::getInstance(); }
单例模式类:
Director //导演类
FileUtils // Helper class to handle file operations
//处理文件操作的Helper类
LuaEngine //The Lua engine integrated into the cocos2d-x to process the interactive operation between lua and c++
//Lua脚本集成到了cocos2d-x来处理lua和C++之间的交互操作
HttpClient //Singleton that handles asynchrounous http requests.
//处理异步HTTP请求
SocketIO //provide static creation method as well as registry of all sockets.
UserDefault //数据存储 bool, int, float, double, string
SimpleAudioEngine //声音
Animation3DCache , AnimationCache , Sprite3DCache , Sprite3DMaterialCache , SpriteFrameCache , TextureCache ,
4.Ref
Ref中就是维护了一个计数器,用于判断该继承于Ref的对象是否应该delete
class CC_DLL Ref{public: //计数加1 void retain(); //计数减1,如果为0,删除对象 void release(); //添加到对象池中,别忘了PoolManager(对象池管理器) 管理AutoreleasePool(对象池),AutoreleasePool管理Ref Ref* autorelease(); //得到当前的计数 unsigned int getReferenceCount() const;};
5.CCPont->Vec2
ccp,CCPointZero替换为Vec2,Vec2::ZERO
setPosition(ccp(x,y))替换为setPosition(x,y)
inline Vec2::Vec2(float xx, float yy): x(xx), y(yy){}
重载运算符
+ += -(减) -= * *= -(negation负) / < > == !=
Vec2(p1)+Vec2(p2)等价于Vec2(p1.x+p2.x,p1.y+p2.y)
6.事件触发机制
三、CocoStudio
//包含头文件、命名空间#include "cocostudio/CocoStudio.h"#include "ui/CocosGUI.h"using namespace cocostudio::timeline;//使用 bool HelloWorld::init(){ auto rootNode = CSLoader::createNode("MainScene.csb"); addChild(rootNode); return true;}
四、Cocos2d-x
1.两阶段构造器
MyClass::MyClass() // c++ class constructor
:_data(NULL) // set all member variables to default values
,_flag(false)
,_count(0)
{
memset(_array, 0, sizeof(_array)); // only set default values here, but not logics
}
我们之所以不应在这里编写任何逻辑,是因为C++默认构造器不能返回表明我们逻辑正确与否的bool 值。
第二阶段是调用MyClass::init()函数。
cocos2d-x v3.0 Release Notes
Highlights of v3.0
- Replaced Objective-C patters with C++ (C++11) patterns and best practices
- Improved Labels
- Improved renderer
- New Event Dispatcher
- Physics integration
- New GUI
- JavaScript remote debugger
- Remote Console support
- Refactor Image - release memory in time and uniform the api of supported file format
- Automatically generated Lua bindings, add LuaJavaBridge and LuaObjcBridge
- Templated containers
Features in detail
C++11 features
Feature added in v3.0-pre-alpha0
A subset of C++11 features are being used in cocos2d-x:
std::function
, including lambda objects for callbacks- strongly typed enums, for most of the cocos2d-x enums and constants
std::thread
for threadingoverride
context keyword, for overriden methods
std::function
CallFunc
can be created with anstd::function<void()>
CallFuncN
can be created with anstd::function<void(Node*)>
CallFuncND
andCallFuncO
were removed since it can be created with simulated withCallFuncN
andCallFunc
. See ActionsTest.cpp for more examplesMenuItem
supportsstd::function<void(Node*)>
as callbacks
CallFunc
example:
MenuItem
example:
strongly typed enums
Feature added in v3.0-pre-alpha0
Constants and enums that started with k
, and that usually were defined as int
or as simple enum
where replaced with strongly typed enums ( enum class
) to prevent collisions and type errors. The new format is:
| v2.1 | v3.0 || kTypeValue | Type::VALUE |
Examples:
| v2.1 | v3.0 || kCCTexture2DPixelFormat_RGBA8888 | Texture2D::PixelFormat::RGBA8888 || kCCDirectorProjectionCustom | Director::Projection::CUSTOM || ccGREEN | Color3B::GREEN || CCPointZero | Point::ZERO || CCSizeZero | Size::ZERO |
The old values can still be used, but are not deprecated.
override
To catch possible errors while overriding methods, subclasses with override methods have the override
context keyword. Example:
Removed Objective-C patterns
Feature added in v3.0-pre-alpha0
No more 'CC' prefix for C++ classes and free functions
Changes in classes
Since cocos2d-x already uses the cocos2d
namespace, there is not need to add the prefix CC
to all its classes.
Examples:
| v2.1 | v3.0 || CCSprite | Sprite || CCNode | Node || CCDirector | Director || etc... |
v2.1 class names are still available, but they were tagged as deprecated.
Changes in free functions
For the drawing primitives:
- They were added in the
DrawPrimitives
namespace - The
cc
prefix was removed
For the gl proxy functions:
- They were added in the
GL
namespace - The
ccGL
prefix was removed
Examples:
| v2.1 | v3.0 || ccDrawPoint() | DrawPrimitives::drawPoint() || ccDrawCircle() | DrawPrimitives::drawCircle() || ccGLBlendFunc() | GL::blendFunc() || ccGLBindTexture2D() | GL::bindTexture2D() || etc... |
v2.1 free functions are still available, but they were tagged as deprecated.
clone() instead of copy()
clone()
returns an autoreleased version of the copy.
copy()
is no longer supported. If you use it, it will compile, but the code will crash.
Example:
Singletons use getInstance() and destroyInstance()
All singletons use getInstance()
and destroyInstance()
(if applicable) to get and destroy the instance.
Examples:
| v2.1 | v3.0 || CCDirector->sharedDirector() | Director->getInstance() || CCDirector->endDirector() | Director->destroyInstance() || etc... |
v2.1 methods are still available, but they were tagged as deprecated.
getters
Getters now use the get
prefix.
Examples:
| v2.1 | v3.0* || node->boundingBox() | node->getBoundingBox() || sprite->nodeToParentTransform() | sprite->getNodeToParentTransform() || etc... |
And getters were also tagged as const
in their declaration. Example:
v2.1 methods are still available, but they were tagged as deprecated.
POD types
Methods that were receiving POD types as arguments (eg: TexParams
, Point
, Size
, etc.) are being passed as const
reference.
Example:
New Renderer
Feature added in v3.0-beta
The renderer functionality has been decoupled from the Scene graph / Node logic. A new object called Renderer
is responsible for rendering the object.
Auto-batching and auto-culling support has been added.
Please, see this document for detail information about its internal funcitonality:https://docs.google.com/document/d/17zjC55vbP_PYTftTZEuvqXuMb9PbYNxRFu0EGTULPK8/edit
Improved LabelTTF / LabelBMFont
Feature added in v3.0-alpha0
New EventDispatcher
Feature added in v3.0-alpha0
All events like touch event, keyboard event, acceleration event and custom event are dispatched by EventDispatcher
.TouchDispatcher
, KeypadDispatcher
, KeyboardDispatcher
, AccelerometerDispatcher
were removed.
Adding Touch Event Listener
For TouchOneByOne:
For TouchAllAtOnce
Adding Mouse Event Listener
Adding A Keyboard Event Listener
Adding An Acceleration Event Listener
Adding A Custom Event Listener
Dispatching A Custom Event
Setting Fixed Priority For A Listener
Removing Event Listener
Removing A Specified Event Listener
Removing Custom Event Listener
Removing All Listeners For An Event Listener Type
Removing All Listeners
Physics Integration
Feature added in v3.0-pre-alpha0
Physics integration have five concepts: PhysicsWorld
, PhysicsBody
, PhysicsShape
, PhysicsJoint
and PhysicsContact
. You must define CC_USE_PHYSICS
macro in ccConfig.h
to use the physics API.
PhysicsWorld
A PhysicsWorld
object simulates collisions and other physical properties, you do not create it directly, you can get it from scene which create with physics.
PhysicsBody
A PhysicsBody
object is used to add physics simulation to a node. If you create a PhysicsBody
and set it to a node, and add the node the a scene which create with physics, it will perform the physics simulation when update.
PhysicsShape
A PhysicsShape
object is a shape that make the body can have collisions. you can add one or more PhysicsShape
to aPhysicsBody
. Shape classes: PhysicsShapeCircle
, PhysicsShapeBox
, PhysicsShapePolygon
, PhysicsShapeEdgeSegment
,PhysicsShapeEdgeBox
, PhysicsShapeEdgePolygon
, PhysicsShapeEdgeChain
.
PhysicsJoint
A PhysicsJoint
object connects two physics bodies together so that they are simulated together by the physics world. Joint classes: PhysicsJointFixed
, PhysicsJointLimit
, PhysicsJointPin
, PhysicsJointDistance
, PhysicsJointSpring
,PhysicsJointGroove
, PhysicsJointRotarySpring
, PhysicsJointRotaryLimit
, PhysicsJointRatchet
, PhysicsJointGear
,PhysicsJointMotor
.
PhysicsContact
A PhysicsContact
object is created automatically to describes a contact between two physical bodies in a PhysicsWorld
. you can control the contact behavior from the physics contact event listener. Other classes contain the contact information:PhysicsContactPreSolve
, PhysicsContactPostSolve
. The event listener for physics: EventListenerPhysicsContact
,EventListenerPhysicsContactWithBodies
, EventListenerPhysicsContactWithShapes
, EventListenerPhysicsContactWithGroup
.
Misc API Changes
ccTypes.h
Remove cc prefix for structure names in ccTypes.h, move global functions into static member functions, and move global constants into const static member variables.
| v2.1 struct names | v3.0 struct names || ccColor3B | Color3B || ccColor4B | Color4B || ccColor4F | Color4F || ccVertex2F | Vertex2F || ccVertex3F | Vertex3F || ccTex2F | Tex2F || ccPointSprite | PointSprite || ccQuad2 | Quad2 || ccQuad3 | Quad3 || ccV2F_C4B_T2F | V2F_C4B_T2F || ccV2F_C4F_T2F | V2F_C4F_T2F || ccV3F_C4B_T2F | V3F_C4B_T2F || ccV2F_C4B_T2F_Triangle | V2F_C4B_T2F_Triangle || ccV2F_C4B_T2F_Quad | V2F_C4B_T2F_Quad || ccV3F_C4B_T2F_Quad | V3F_C4B_T2F_Quad || ccV2F_C4F_T2F_Quad | V2F_C4F_T2F_Quad || ccBlendFunc | BlendFunc || ccT2F_Quad | T2F_Quad || ccAnimationFrameData | AnimationFrameData |
Global functions changed example
deprecated functions and global variables
| v2.1 names | v3.0 names || ccp | Point || ccpNeg | Point::- || ccpAdd | Point::+ || ccpSub | Point::- || ccpMult | Point::* || ccpMidpoint | Point::getMidpoint || ccpDot | Point::dot || ccpCrosss | Point::cross || ccpPerp | Point::getPerp || ccpRPerp | Point::getRPerp || ccpProject | Point::project || ccpRotate | Point::rotate || ccpUnrotate | Point::unrotate || ccpLengthSQ | Point::getLengthSq() || ccpDistanceSQ | Point::getDistanceSq || ccpLength | Point::getLength || ccpDistance | Point::getDistance || ccpNormalize | Point::normalize || ccpForAngle | Point::forAngle || ccpToAngle | Point::getAngle || ccpClamp | Point::getClampPoint || ccpFromSize | Point::Point || ccpCompOp | Point::compOp || ccpLerp | Point::lerp || ccpFuzzyEqual | Point::fuzzyEqual || ccpCompMult | Point::Point || ccpAngleSigned | Point::getAngle || ccpAngle | Point::getAngle || ccpRotateByAngle | Point::rotateByAngle || ccpLineInersect | Point::isLineIntersect || ccpSegmentIntersect | Point::isSegmentIntersect || ccpIntersectPoint | Point::getIntersectPoint || CCPointMake | Point::Point || CCSizeMake | Size::Size || CCRectMake | Rect::Rect || PointZero | Point::ZERO || SizeZero | Size::ZERO || RectZero | Rect::ZERO || TiledGrid3DAction::tile | TiledGrid3DAction::getTile || TiledGrid3DAction::originalTile | TiledGrid3DAction::getOriginalTile || TiledGrid3D::tile | TiledGrid3D::getTile || TiledGrid3D::originalTile | TiledGrid3D::getOriginalTile || Grid3DAction::vertex | Grid3DAction::getVertex || Grid3DAction::originalVertex | Grid3DAction::getOriginalVertex || Grid3D::vertex | Grid3D::getVertex || Grid3D::originalVertex | Grid3D::getOriginalVertex || Configuration::sharedConfiguration | Configuration::getInstance || Configuration::purgeConfiguration | Configuration::destroyInstance() || Director::sharedDirector() | Director::getInstance() || FileUtils::sharedFileUtils | FileUtils::getInstance || FileUtils::purgeFileUtils | FileUtils::destroyInstance || EGLView::sharedOpenGLView | EGLView::getInstance || ShaderCache::sharedShaderCache | ShaderCache::getInstance || ShaderCache::purgeSharedShaderCache | ShaderCache::destroyInstance || AnimationCache::sharedAnimationCache | AnimationCache::getInstance || AnimationCache::purgeSharedAnimationCache | AnimationCache::destroyInstance || SpriteFrameCache::sharedSpriteFrameCache | SpriteFrameCache::getInstance || SpriteFrameCache:: purgeSharedSpriteFrameCache | SpriteFrameCache::destroyInstance || NotificationCenter::sharedNotificationCenter | NotificationCenter::getInstance || NotificationCenter:: purgeNotificationCenter | NotificationCenter::destroyInstance || Profiler::sharedProfiler | Profiler::getInstance || UserDefault::sharedUserDefault | UserDefault::getInstance || UserDefault::purgeSharedUserDefault | UserDefault::destroyInstance || Application::sharedApplication | Application::getInstance || ccc3() | Color3B() || ccc3BEqual() | Color3B::equals() || ccc4() | Color4B() || ccc4FFromccc3B() | Color4F() || ccc4f() | Color4F() || ccc4FFromccc4B() | Color4F() || ccc4BFromccc4F() | Color4B() || ccc4FEqual() | Color4F::equals() || ccWHITE | Color3B::WHITE || ccYELLOW | Color3B::YELLOW || ccBLUE | Color3B::BLUE || ccGREEN | Color3B::GREEN || ccRED | Color3B::RED || ccMAGENTA | Color3B::MAGENTA || ccBLACK | Color3B::BLACK || ccORANGE | Color3B::ORANGE || ccGRAY | Color3B::GRAY || kBlendFuncDisable | BlendFunc::BLEND_FUNC_DISABLE |
Changes in the Lua bindings
Use bindings-generator tool for Lua binding
Only configurating the *.ini files in the tools/tolua folder,not to write a lot of *.pkg files
Use ScriptHandlerMgr to manage the register and unregister of Lua function
When we want to add register and unregister functions of Lua function for class, we need to change the declarative and defined files and then bind to Lua. In v3.0, we use the ScriptHandlerMgr
. As an example, lets see the MenuItem
class: In the 2.x version, we needed to add a declaration in the MenuItem header file:
then implement them in the .cpp file. In the Lua script ,we use it as follow:
In v3.0 version, we only need to add the HandlerType
enum in the ScriptHandlerMgr
, and the implementation in luascript as follow:
Use "cc" and "ccs" as module name
Deprecated funtions, tables and classes
Add a lot of deprecate funtions、table and classes to support 2.x version as far as possible Note:Rect does not support the origin and size member variables
Use the Lua table instead of the some structs and classes binding
Point、Size、Rect、Color3b、Color4b、Color4F、AffineTransform、FontDefinition、Array、Dictionary、PointArray are not bound. The difference is as follow:
Global functions about these classes are changed as follow:
Through the funtions of the LuaBasicConversion file,they can be converted the Lua table when they are as a parameter in the bindings generator.
- Cocos2d-x-3.6学习(三)---- TestCpp学习
- Cocos2d-x学习笔记(17)(TestCpp源码分析-1)
- Cocos2d-x学习笔记(18)(TestCpp源码分析-2)
- Cocos2d-x学习笔记(19)(TestCpp源码分析-3)
- Cocos2d-x学习笔记(20)(TestCpp源码分析-4)
- Cocos2d-x新手学习之TestCpp项目结构分析(第四篇)[版本:cocos2d-x-3.1.1]
- Cocos2D-X学习笔记(三)
- cocos2d-x+cocosbuilder 学习笔记 (三)
- cocos2D-x 学习之路(三)
- cocos2d-x TestCpp中的 多点触控MutiTouchTest、两点手势缩放算法---cocos2d-x学习之路[1]
- Cocos2d-x 2.x TestCPP启用box2d(CC_ENABLE_BOX2D_INTEGRATION)
- cocos2d-x的TestCpp分析
- cocos2d-x 笔记(四) TestCpp源码分析:control
- cocos2d-x 笔记(五) TestCpp源码分析:Actions
- Cocos2d-x学习笔记(三)CCNode分析
- Cocos2d-x学习笔记(三)-------->Scene场景
- Cocos2d-x结构学习(三)CCTouchDelegate、CCAccelerometerDelegate、CCKeypadDelegate
- Cocos2d-x学习笔记(三)—— 坐标系
- 基于Android平台的串口通信实现
- Java基础---集合Collection
- ios系统自带推送(ios自学笔记)
- Linux+Nginx+Tomcat 多域名,多应用在同一服务器的配置
- Java遍历列出某一目录下的文件及文件夹,寻找某一指定文件
- Cocos2d-x-3.6学习(三)---- TestCpp学习
- OpenGL ES2.0 基本编程
- [转]并发下常见的加锁及锁的PHP具体实现
- HDU 1011 Starship Troopers(树形dp+背包)
- 黑马程序员————第六天
- C#高级编程三十七天----结构比较
- 修改u-boot与Linux调试串口以及文件系统显示终端串口
- text
- Linux安装xwindow图形界面