新建一个hellworld 工程然后再Hellworld里面添加一个对象 CCRenderTexture * darknessLayer;
然后在在hellord init函数中添加代码
CCSprite
*sprite1=LightCCSprite::spriteWithFile("light.png");//继承ccsprite新建对象
sprite1->setPosition(ccp(100,100));
this->addChild(sprite1,2);
sprite1->runAction(CCRepeatForever::actionWithAction((CCActionInterval
*)CCSequence::actions(CCMoveBy::actionWithDuration(3.0f,ccp(300,0)),CCMoveBy::actionWithDuration(0.1f,ccp(-300,0)),NULL)));
darknessLayer =
CCRenderTexture::renderTextureWithWidthAn
size.height);
darknessLayer->setPosition(ccp( size.width /2 ,
size.height/2
));
this->addChild(darknessLayer,20);
darknessLayer->clear(0,0,0,0.5f);//设置黑夜笼罩
覆盖draw函数
void
HelloWorld::draw(){
darknessLayer->clear(0,0,0,0.8f);//必须的不然产生光亮区域不还原。。。。。
CCLayer::draw();
}
LightCCSprite需要覆盖两个函数
static CCSprite *spriteWithFile(const char *
filename){
CCSprite *pobSprite = new
LightCCSprite();//这里才会调用draw,而不是CCSprite的draw
if (pobSprite
&&
pobSprite->initWithFile(filename))
{
pobSprite->autorelease();
return
pobSprite;
}
CC_SAFE_DELETE(pobSprite);
return
NULL;
}
void draw(){
//CCSprite::draw();//如果不取消的话如果两个lightCCSPrite对象只有一个会产生亮光
((HelloWorld*)getParent())->darknessLayer->begin();
// glClear(GL_COLOR_BUFFER_BIT);
glBlendFunc(GL_ZERO,
GL_ONE_MINUS_SRC_ALPHA); //
glColorMask(0.0f, 0.0f, 0.0f,
1.0f);//关键句
#define kQuadSize sizeof(m_sQuad.bl)
if
(m_pobTexture)
{
glBindTexture(GL_TEXTURE_2D,
m_pobTexture->getName());
}
else
{
glBindTexture(GL_TEXTURE_2D,
0);
}
long offset = (long)&m_sQuad;
//
vertex
int diff = offsetof(ccV3F_C4B_T2F,
vertices);
glVertexPointer(3, GL_FLOAT, kQuadSize, (void*)(offset +
diff));
// color
diff = offsetof( ccV3F_C4B_T2F,
colors);
glColorPointer(4, GL_UNSIGNED_BYTE, kQuadSize, (void*)(offset
+ diff));
// tex coords
diff = offsetof( ccV3F_C4B_T2F,
texCoords);
glTexCoordPointer(2, GL_FLOAT, kQuadSize, (void*)(offset +
diff));
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glColorMask(1.0f, 1.0f, 1.0f,
1.0f);
((HelloWorld*)getParent())->darknessLayer->end();
}
效果图