转自:http://blog.csdn.net/xujiezhige/article/details/8448524#
常见的手电筒效果,可以通过CCRenderTexture来实现。主要是通过修改渲染表面的alpha值来达到手电筒光照范围内的透明效果。此方法纯原创,如有雷同,英雄所见略同。这里由于本人没有什么图片,这里直接用矩形区域来代替圆形区域。通过以下几个基本步骤来完成这个效果。
//create render target CCRenderTexture* pRenderTexture = CCRenderTexture::create( BY_WIN_SIZE_WIDTH, BY_WIN_SIZE_HEIGHT ); //render the target to black pRenderTexture->begin(); glDisable( GL_BLEND ); ccDrawSolidRect( ccp( 0, 0 ), ccp( BY_WIN_SIZE_WIDTH, BY_WIN_SIZE_HEIGHT ), ccc4f( 0, 0, 0, 1 ) ); glEnable( GL_BLEND ); pRenderTexture->end(); //set the render target over the scene pRenderTexture->setPosition( ccp( BY_WIN_SIZE_WIDTH_HALF, BY_WIN_SIZE_HEIGHT_HALF ) ); addChild( pRenderTexture, 2, 1000 ); //render target is the sprite's texture. //set the sprite render parms. ccBlendFunc bf = { GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA }; pRenderTexture->getSprite()->setBlendFunc( bf );
在ccTouchBegan()函数中透明处用户点击的区域
//get transparent area CCPoint ptBottomLeftCorner = ccpSub( pTouch->getLocation(), ccp( 200, 200 ) ); CCPoint ptTopRightCorner = ccpAdd( pTouch->getLocation(), ccp( 200, 200 ) ); //set the area transparent BY_GET_CHILD( CCRenderTexture, 1000 )->begin(); glDisable( GL_BLEND ); ccDrawSolidRect( ptBottomLeftCorner, ptTopRightCorner, ccc4f( 0, 0, 0, 0 ) ); glEnable( GL_BLEND ); BY_GET_CHILD( CCRenderTexture, 1000 )->end();
在ccTouchMoved()函数中,首先抹黑原来的区域(这里为了保险,我们直接抹黑整个渲染表面),另外透明出新的区域
//get transparent area CCPoint ptBottomLeftCorner = ccpSub( pTouch->getLocation(), ccp( 200, 200 ) ); CCPoint ptTopRightCorner = ccpAdd( pTouch->getLocation(), ccp( 200, 200 ) ); BY_GET_CHILD( CCRenderTexture, 1000 )->begin(); glDisable( GL_BLEND ); //set the render target black ccDrawSolidRect( CCPointZero, ccp( BY_WIN_SIZE_WIDTH, BY_WIN_SIZE_HEIGHT ), ccc4f( 0, 0, 0, 1 ) ); //set the new area transparent ccDrawSolidRect( ptBottomLeftCorner, ptTopRightCorner, ccc4f( 0, 0, 0, 0 ) ); glEnable( GL_BLEND ); BY_GET_CHILD( CCRenderTexture, 1000 )->end();
在ccTouchEnded()和ccTouchCanceled()函数中,抹黑整块渲染表面。
BY_GET_CHILD( CCRenderTexture, 1000 )->begin(); glDisable( GL_BLEND ); ccDrawSolidRect( CCPointZero, ccp( BY_WIN_SIZE_WIDTH, BY_WIN_SIZE_HEIGHT ), ccc4f( 0, 0, 0, 1 ) ); glEnable( GL_BLEND ); BY_GET_CHILD( CCRenderTexture, 1000 )->end();