我试图在这里实现类似聚光灯演示:http: //www.supersuraccoon-cocos2d.com/2011/09/09/spot-light-demo/
我设法在渲染纹理中添加了几个聚光灯,但我仍然有一个问题,如何在不清除整个纹理的情况下只移除一个聚光灯?
这是 CCSpotLight.m 中的绘图代码:
-(void) drawSpotLight
{
int segs = 15;
GLfloat *vertices = malloc( sizeof(GLfloat)*2*(segs));
GLfloat *coordinates = malloc( sizeof(GLfloat)*2*(segs));
ccColor4B *colors = malloc( sizeof(ccColor4B)*(segs));
memset(vertices,0, sizeof(GLfloat)*2*(segs));//Set first (3rd param) of the block of memory pointed by vertices to 0
memset(coordinates,0, sizeof(GLfloat)*2*(segs));
colors[0] = ccc4(0, 0, 0, 255);//opaque
for (int i = 1; i < segs; i++)
{
colors[i] = ccc4(0, 0, 0, 0);//transparent
}
const float coef = 2.0f * (float)M_PI/(segs-2) ;
vertices[0] = self.position.x;
vertices[1] = self.position.y;
coordinates[0] = self.position.x;
coordinates[1] = (contentSize_.height-self.position.y);
for(int i=1;i<=segs;i++)
{
float rads = i*coef;
float j = self.spotLightRadius * cosf(rads) + self.position.x;
float k = self.spotLightRadius * sinf(rads) + self.position.y;
vertices[i*2] = j;
vertices[i*2+1] = k;
coordinates[i*2] = (j);
coordinates[i*2+1] = (contentSize_.height-k);
}
// Update the render texture
[self.renderTexture begin];
glBindTexture(GL_TEXTURE_2D, (GLuint)self.renderTexture);//bind a named texture to a texturing target (2d texture)
glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_ALPHA);
glColorMask(0.0f, 0.0f, 0.0f, 1.0f);//enable and disable writing of frame buffer color components
glVertexPointer(2, GL_FLOAT, 0, vertices);//define an array of vertex data
glTexCoordPointer(2, GL_FLOAT, 0, coordinates);
glColorPointer(4, GL_UNSIGNED_BYTE, 0, colors);
glDrawArrays(GL_TRIANGLE_FAN, 0, segs);
glColorMask(1.0f, 1.0f, 1.0f, 1.0f);
glBlendFunc(CC_BLEND_SRC, CC_BLEND_DST);
[self.renderTexture end];
free(vertices);
free(coordinates);
free(colors);
}
以及 HelloWorldLayer.m 中的实例化代码:
renderLayer = [CCRenderTexture renderTextureWithWidth:480
height:320];
renderLayer.position = ccp(240, 160);
[renderLayer clear:0
g:0
b:0
a:0.5];
[[renderLayer sprite] setBlendFunc: (ccBlendFunc) { GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA }];
[self addChild:renderLayer z:0];
CCSpotLight *spotLight1 = [CCSpotLight initWithRenderTexture:renderLayer
spotLightRadius:60.0f
renderColor:ccc4(0, 0, 0, 255)
x:224
y:160];
[self addChild:spotLight1 z:1];
//adding another spotlight which should be removed when the user touches the screen
CCSpotLight *spotLight2 = [CCSpotLight initWithRenderTexture:renderLayer
spotLightRadius:60.0f
renderColor:ccc4(0, 0, 0, 255)
x:124
y:160];
[self addChild:spotLight2 z:1];//for removing it, I tried [spotLight2 removeFromParentAndCleanup:YES] but it didn't work, no change at all