本文实践自 Ray Wenderlich、Ali Hafizji 的文章《How To Create Dynamic Textures with CCRenderTexture in Cocos2D 2.X》,文中使用Cocos2D,我在这里使用cocos2d-x-3.0alpha0进行学习和移植。在这篇文章,将会学习到如何创建实时纹理、如何用Gimp创建无缝拼接纹理、如何混合阴影和光照到纹理上以显现逼真效果、如何创建条纹纹理、如何设置纹理重复等等。
步骤如下:
1.新建Cocos2d-win32工程,工程名为"TinySeal",勾选"Box2D"选项(后续文章会使用到),勾选"Simple Audio Engine in Cocos Denshion"选项;
2.打开HelloWorldScene.cpp文件,在添加如下方法:
Sprite* HelloWorld::spriteWithColor(cocos2d::Color4F bgColor, float textureWidth, float textureHight)
{
//1: Create new RenderTexture
RenderTexture* rt = RenderTexture::create(textureWidth, textureHight);
//2: Call RenderTexture:begin
rt->beginWithClear(bgColor.r, bgColor.g, bgColor.b, bgColor.a);
//3: Draw into the texture
//You'll add this later
//4: Call RenderTexture:end
rt->end();
return Sprite::createWithTexture(rt->getSprite()->getTexture());
}
正如你所见,这5个步骤是用来创建动态纹理的,具体描述如下:
①.创建一个新的CCRenderTexture:指定所要创建纹理的宽度和高度。
②.调用CCRenderTexture的begin方法:设置OpenGL以便之后的任何图形绘制都在CCRenderTexture上,而不是屏幕上。
③.绘制纹理:使用原始的OpenGL命令来绘制,或通过调用现有的Cocos2D对象的visit方法。
④.调用CCRenderTexture的end方法:渲染纹理,关闭绘制到纹理上。
⑤.以纹理创建一个新的精灵:以CCRenderTexture的getSprite()->getTexture()来创建一个新的精灵。
注意这里不是调用CCRenderTexture:begin方法,而是调用一个更方便的方法beginWithClear,可以在绘制之前,用特定的颜色来清除纹理。
3.接着打开HelloWorldScene.h文件,添加如下代码:
cocos2d::Sprite* _background;
打开
HelloWorldScene.cpp
文件,在构造函数里添加如下代码:
_background = NULL;
修改
init
函数为如下:
bool HelloWorld::init()
{
bool bRet = false;
do {
CC_BREAK_IF(!Layer::init());
bRet = true;
} while (0);
return bRet;
}
添加以下方法:
Color4F HelloWorld::randomBrightColor()
{
while (true) {
float requiredBrightness = 192;
Color4B randomColor = Color4B(rand() % 255,
rand() % 255,
rand() % 255,
rand() % 255);
if (randomColor.r > requiredBrightness ||
randomColor.g > requiredBrightness ||
randomColor.b > requiredBrightness
) {
return Color4F(randomColor.r/255.f, randomColor.g/255.f, randomColor.b/255.f, randomColor.a/255.f);
}
}
}
void HelloWorld::genBackground()
{
if (_background) {
_background->removeFromParentAndCleanup(true);
}
Color4F bgColor = this->randomBrightColor();
_background = this->spriteWithColor(bgColor, 512, 512);
Size winSize = Director::getInstance()->getWinSize();
_background->setPosition(Point(winSize.width / 2, winSize.height / 2));
this->cocos2d::Node::addChild(_background, -1);
}
void HelloWorld::onEnter()
{
Layer::onEnter();
this->genBackground();
this->setTouchEnabled(true);
}
void HelloWorld::onTouchesBegan(const std::vector<Touch *> &touches, cocos2d::Event *event)
{
this->genBackground();
}
randomBrightColor
是一个辅助方法,用来创建随机颜色。注意到这里是使用ccc4B,所以可以指定R/G/B/A值在0-255范围内,并且确保至少其中之一大于192,这样就不会得到较深的颜色。然后再将颜色转换成ccc4F。
genBackground
方法调用
spriteWithColor