0

我正在尝试使用这个 raywenderlich 教程。我对 CSEGrass 示例(页面按钮)感兴趣。

我确实尝试在带有 alpha 通道的小图像上运行着色器,该通道在蓝色背景后添加到场景中。这是代码(几乎与教程相同,见下文)。我期待红色图像显示没有黑色边框。

这是图像:

图片

结果是这样的: 图像弯曲

图像弯曲 2

我对此完全没有经验,但我猜所写的着色器无法识别透明像素并将它们绘制为黑色..在代码(第 5 节)中,似乎绘制的是正常颜色,实际上它应该是透明的..看起来透明像素有一个对应于黑色的rgb值..

vec3 normalColor = texture2D(u_texture, fract(vec2(v_texCoord.x + offset, v_texCoord.y))).rgb;

我有点失落。我在这里发布代码:

 CCSprite *background = [CCSprite spriteWithFile:@"icewallpaper.png"];
        background.anchorPoint = CGPointMake(0.5f, 0.5f);
        background.position = CGPointMake( 160.0f, 240.0f);
        [self addChild:background];

        // 1
        sprite = [CCSprite spriteWithFile:@"grass.png"];
        sprite.anchorPoint =CGPointMake(0.5f, 0.5f);
        sprite.position =  CGPointMake( 160.0f, 240.0f);
        [self addChild:sprite z:0 tag:69];

        CCSprite *altra = [CCSprite spriteWithFile:@"Icon-Small.png"];
        altra.anchorPoint = CGPointMake(0.5, 0.5f);
        altra.position = CGPointMake(20.0f, 300.0f);
        [self addChild:altra z:0 tag:99];


        // 2
        const GLchar * fragmentSource = (GLchar*) [[NSString stringWithContentsOfFile:[CCFileUtils fullPathFromRelativePath:@"CSEGrass.fsh"] encoding:NSUTF8StringEncoding error:nil] UTF8String];
        sprite.shaderProgram = [[CCGLProgram alloc] initWithVertexShaderByteArray:ccPositionTextureA8Color_vert
                                                          fragmentShaderByteArray:fragmentSource];
        [sprite.shaderProgram addAttribute:kCCAttributeNamePosition index:kCCVertexAttrib_Position];
        [sprite.shaderProgram addAttribute:kCCAttributeNameTexCoord index:kCCVertexAttrib_TexCoords];
        [sprite.shaderProgram link];
        [sprite.shaderProgram updateUniforms];

        // 3
        timeUniformLocation = glGetUniformLocation(sprite.shaderProgram->program_, "u_time");

        // 4
        [self scheduleUpdate];

        // 5
        [sprite.shaderProgram use];

这是着色器文件CSEGrass.fsh

#ifdef GL_ES
precision mediump float;
#endif

varying vec2 v_texCoord;
uniform sampler2D u_texture;
uniform float u_time;

// 1
const float speed = 4.0;
const float bendFactor = 0.5;
void main()
{
    // 2
    float height = 0.0 + v_texCoord.y;
    // 3
    float offset = pow(height, 2.5);

    // 4 multiply by sin since it gives us nice bending
    offset *= (sin(u_time * speed) * bendFactor);

    // 5
    vec3 normalColor = texture2D(u_texture, fract(vec2(v_texCoord.x + offset, v_texCoord.y))).rgb;
    gl_FragColor = vec4(normalColor, 1);
}
4

1 回答 1

1
vec3 normalColor = texture2D(u_texture, fract(vec2(v_texCoord.x + offset, v_texCoord.y))).rgb;
gl_FragColor = vec4(normalColor, 1);

您正在获取纹理颜色的 RGB 值并将它们与 alpha 值一起使用。因此,(0, 0, 0, 0) 变为 (0, 0, 0, 1),纯黑色。解决方案:使用纹理中的 alpha 值。

gl_FragColor = texture2D(u_texture, fract(vec2(v_texCoord.x + offset, v_texCoord.y))).rgba;
于 2012-08-14T20:24:13.400 回答