cocos2d-x实现透视朦胧光照效果
新建一个hellworld 工程然后再Hellworld里面添加一个对象 CCRenderTexture * darknessLayer;
然后在在hellord init函数中添加代码
1 CCSprite 2 *sprite1=LightCCSprite::spriteWithFile("light.png");//继承ccsprite新建对象 3 sprite1->setPosition(ccp(100,100)); 4 this->addChild(sprite1,2); 5 sprite1->runAction(CCRepeatForever::actionWithAction((CCActionInterval 6 *)CCSequence::actions(CCMoveBy::actionWithDuration(3.0f,ccp(300,0)),CCMoveBy::actionWithDuration(0.1f,ccp(-300,0)),NULL))); 7 8 darknessLayer = 9 CCRenderTexture::renderTextureWithWidthAndHeight(size.width, 10 size.height); 11 darknessLayer->setPosition(ccp( size.width /2 , 12 size.height/2 13 )); 14 this->addChild(darknessLayer,20); 15 darknessLayer->clear(0,0,0,0.5f);//设置黑夜笼罩 16 17 18 19 覆盖draw函数 20 21 void 22 HelloWorld::draw(){ 23 darknessLayer->clear(0,0,0,0.8f);//必须的不然产生光亮区域不还原。。。。。 24 CCLayer::draw(); 25 26 } 27 28 29 30 31 LightCCSprite需要覆盖两个函数 32 33 34 static CCSprite *spriteWithFile(const char * 35 filename){ 36 CCSprite *pobSprite = new 37 LightCCSprite();//这里才会调用draw,而不是CCSprite的draw 38 if (pobSprite 39 && 40 pobSprite->initWithFile(filename)) 41 { 42 pobSprite->autorelease(); 43 return 44 pobSprite; 45 } 46 CC_SAFE_DELETE(pobSprite); 47 return 48 NULL; 49 } 50 void draw(){ 51 52 53 //CCSprite::draw();//如果不取消的话如果两个lightCCSPrite对象只有一个会产生亮光 54 55 ((HelloWorld*)getParent())->darknessLayer->begin(); 56 // glClear(GL_COLOR_BUFFER_BIT); 57 glBlendFunc(GL_ZERO, 58 GL_ONE_MINUS_SRC_ALPHA); // 59 glColorMask(0.0f, 0.0f, 0.0f, 60 1.0f);//关键句 61 62 #define kQuadSize sizeof(m_sQuad.bl) 63 if 64 (m_pobTexture) 65 { 66 glBindTexture(GL_TEXTURE_2D, 67 m_pobTexture->getName()); 68 } 69 else 70 { 71 glBindTexture(GL_TEXTURE_2D, 72 0); 73 } 74 long offset = (long)&m_sQuad; 75 // 76 vertex 77 int diff = offsetof(ccV3F_C4B_T2F, 78 vertices); 79 glVertexPointer(3, GL_FLOAT, kQuadSize, (void*)(offset + 80 diff)); 81 // color 82 diff = offsetof( ccV3F_C4B_T2F, 83 colors); 84 glColorPointer(4, GL_UNSIGNED_BYTE, kQuadSize, (void*)(offset 85 + diff)); 86 // tex coords 87 diff = offsetof( ccV3F_C4B_T2F, 88 texCoords); 89 glTexCoordPointer(2, GL_FLOAT, kQuadSize, (void*)(offset + 90 diff)); 91 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); 92 93 94 95 96 glColorMask(1.0f, 1.0f, 1.0f, 97 1.0f); 98 ((HelloWorld*)getParent())->darknessLayer->end(); 99 }
效果图