(1)异步加载图片资源
当游戏中需要使用的纹理图过多时,如果在进入界面加载,会导致界面长时间处于等待状态,影响体验。所以最好的情况就是设置一个加载界面,异步加载图片资源,主要API如下所示。
auto texture=Director::getInstance()->getTextureCache();
texture->addImageAsync(const std::string &filepath, const std::function<void(Texture2D*)>& callback);
(2)异步加载3D模型
3D模型如obj等的加载也是需要大量的时间的,所以此处也是采用相同的策略,异步加载。主要API如下所示。
Sprite3D::createAsync(const std::string &modelPath, const std::function<void(Sprite3D*, void*)>& callback, void* callbackparam);
Sprite3D::createAsync(path,CC_CALLBACK_2(LoadingLayer::printf,this),(void*)i++);<span style="white-space:pre"> </span>//实例
(3)获得触摸对象
在游戏中,我们经常需要获得点击点处的节点对象,然后对其进行相应的操作,主要使用的是Event类和Touch类。主要API如下所示。
auto target=static_cast<Sprite*>(event->getCurrentTarget());<span style="white-space:pre"> </span>//获得触摸对象
Point location=target->convertToNodeSpace(target->getLocation());<span style="white-space:pre"> </span>//获得精灵位置
注:Touch类常用的方法有:
/** Returns the current touch location in OpenGL coordinates.
*
* @return The current touch location in OpenGL coordinates.
*/
Vec2 getLocation() const;
<pre name="code" class="cpp">/** Returns the delta of 2 current touches locations in screen coordinates.
*
* @return The delta of 2 current touches locations in screen coordinates.
*/
Vec2 getDelta() const;
(4)角度与弧度的相互转化
在进行sin、tan等的函数运算中,参数常常为弧度,所以常常需要进行弧度与角度的转化,所幸的Cocos2d-x引擎提供了相关的API,具体API如下所示。
/** @def CC_DEGREES_TO_RADIANS
converts degrees to radians
*/
#define CC_DEGREES_TO_RADIANS(__ANGLE__) ((__ANGLE__) * 0.01745329252f) // PI / 180
/** @def CC_RADIANS_TO_DEGREES
converts radians to degrees
*/
#define CC_RADIANS_TO_DEGREES(__ANGLE__) ((__ANGLE__) * 57.29577951f) // PI * 180
(5)BillBoard类的使用
BillBoard类主要用于实现3D场景的公告板功能,所谓的公告板,即始终朝向相机所在点,或始终朝向相机局部坐标系的XoY平面的2D精灵。具体API如下所示。
BillBoard *board=BillBoard::create();
board->addChild("精灵即可");
board->setCameraMask((unsigned short)CameraFlag::USER1);
在3D场景中,一般都需要添加环境光,具体API如下所示。
/**
* Creates a ambient light.
* @param color The light's color.
*
* @return The new ambient light.
*/
static AmbientLight* create(const Color3B &color);
项目