cocos2d-x 手电筒效果

时间:2022-09-25 23:36:17

转自: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(
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();
好了,我们实现了这个“矩形"的手电筒效果。最好使用png图片来弄出手电筒光圈和透明区域来。
 
另外:其中BY开头的宏是我个人写的一些宏,以便本人加快编程速度。你可以通过字面意思猜到我的宏实现方法,呵呵。