cocos2d-x 手电筒效果

时间:2023-03-09 20:23:28
cocos2d-x 手电筒效果

转自:http://blog.csdn.net/xujiezhige/article/details/8448524#

常见的手电筒效果,可以通过CCRenderTexture来实现。主要是通过修改渲染表面的alpha值来达到手电筒光照范围内的透明效果。此方法纯原创,如有雷同,英雄所见略同。这里由于本人没有什么图片,这里直接用矩形区域来代替圆形区域。通过以下几个基本步骤来完成这个效果。

  1. 首先创建一个全黑的渲染表明覆盖在场景之上。
    //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( , ), ccp( BY_WIN_SIZE_WIDTH, BY_WIN_SIZE_HEIGHT ), ccc4f( , , , ) );
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, , ); //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( , ) );
CCPoint ptTopRightCorner = ccpAdd( pTouch->getLocation(), ccp( , ) ); //set the area transparent
BY_GET_CHILD( CCRenderTexture, )->begin();
glDisable( GL_BLEND );
ccDrawSolidRect( ptBottomLeftCorner, ptTopRightCorner, ccc4f( , , , ) );
glEnable( GL_BLEND );
BY_GET_CHILD( CCRenderTexture, )->end();

在ccTouchMoved()函数中,首先抹黑原来的区域(这里为了保险,我们直接抹黑整个渲染表面),另外透明出新的区域

    //get transparent area
CCPoint ptBottomLeftCorner = ccpSub( pTouch->getLocation(), ccp( , ) );
CCPoint ptTopRightCorner = ccpAdd( pTouch->getLocation(), ccp( , ) ); BY_GET_CHILD( CCRenderTexture, )->begin();
glDisable( GL_BLEND ); //set the render target black
ccDrawSolidRect( CCPointZero, ccp( BY_WIN_SIZE_WIDTH, BY_WIN_SIZE_HEIGHT ), ccc4f( , , , ) );
//set the new area transparent
ccDrawSolidRect( ptBottomLeftCorner, ptTopRightCorner, ccc4f( , , , ) ); glEnable( GL_BLEND );
BY_GET_CHILD( CCRenderTexture, )->end();

在ccTouchEnded()和ccTouchCanceled()函数中,抹黑整块渲染表面。

    BY_GET_CHILD( CCRenderTexture,  )->begin();
glDisable( GL_BLEND );
ccDrawSolidRect( CCPointZero, ccp( BY_WIN_SIZE_WIDTH, BY_WIN_SIZE_HEIGHT ), ccc4f( , , , ) );
glEnable( GL_BLEND );
BY_GET_CHILD( CCRenderTexture, )->end();
好了,我们实现了这个“矩形"的手电筒效果。最好使用png图片来弄出手电筒光圈和透明区域来。
另外:其中BY开头的宏是我个人写的一些宏,以便本人加快编程速度。你可以通过字面意思猜到我的宏实现方法,呵呵。