我正在尝试调整有关着色器的本教程以在我的游戏中工作,然后我将使用 glsl 来获得我想要的效果。
我用 Box2D 创建了一个 Cocos2d 2.x 项目。Box2D 模板为我提供了一个PhysicsSprite类,这就是我不使用CCSprite. 这是我的初始化方法:
-(id) init
{
    if( (self=[super init])) {
        s = [[CCDirector sharedDirector] winSize];
        // enable events
        self.isTouchEnabled = YES;
        self.isAccelerometerEnabled = YES;
        // init physics
        [self initPhysics];
        //Init shader effects.
        [self initShaderEffects];
        ball = [PhysicsSprite spriteWithFile:@"Ball.png"];
        ball.position = ccp(s.width/2, s.height/2);
        b_body = [self createCirBody:10 andSpr:ball];
        [ball setPhysicsBody:b_body];
        [self addChild:ball];
        b_body->SetLinearVelocity(b2Vec2(1.5f,0));
        [self scheduleUpdate];
    }
    return self;
}
如果排除[self initShaderEffects];我测试过的代码行,到目前为止它可以工作,我得到一个移动的球。这是我的initShaderEffects(这与教程基本相同,除了我使用ball而不是,sprite并且我将fragmentSource初始化更改为使用非弃用方法):
-(void)initShaderEffects {
    const GLchar *fragmentSource = (GLchar*)[[NSString stringWithContentsOfFile:@"MyCustomShader.fsh" encoding:NSUTF8StringEncoding error:nil] UTF8String];
    ball.shaderProgram = [[CCGLProgram alloc] initWithVertexShaderByteArray:ccPositionTextureA8Color_vert fragmentShaderByteArray:fragmentSource];
    [ball.shaderProgram addAttribute:kCCAttributeNamePosition index:kCCVertexAttrib_Position];
    [ball.shaderProgram addAttribute:kCCAttributeNameTexCoord index:kCCVertexAttrib_TexCoords];
    [ball.shaderProgram link];
    [ball.shaderProgram updateUniforms];
    colorRampUniformLocation = glGetUniformLocation(ball.shaderProgram->program_, "u_colorRampTexture"); //EXC_BAD_ACCESS
    glUniform1i(colorRampUniformLocation, 1);
    colorRampTexture = [[CCTextureCache sharedTextureCache] addImage:@"x2.png"];
    [colorRampTexture setAliasTexParameters];
    [ball.shaderProgram use];
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, [colorRampTexture name]);
    glActiveTexture(GL_TEXTURE0);
}
最后是我直接从教程中复制的着色器“MyCustomShader.fsh”:
#ifdef GL_ES
precision mediump float;
#endif
// 1
varying vec2 v_texCoord;
uniform sampler2D u_texture;
uniform sampler2D u_colorRampTexture;
void main()
{ // 2
    vec3 normalColor = texture2D(u_texture, v_texCoord).rgb;
    // 3
    float rampedR = texture2D(u_colorRampTexture, vec2(normalColor.r, 0)).r;
    float rampedG = texture2D(u_colorRampTexture, vec2(normalColor.g, 0)).g;
    float rampedB = texture2D(u_colorRampTexture, vec2(normalColor.b, 0)).b;
    // 4
    gl_FragColor = vec4(rampedR, rampedG, rampedB, 1);
}
EXC_BAD_ACCESS这段代码在我的方法中有评论的那一行给了我 EXC_BAD_ACCESS initShaderEffects。我发现着色器很困难,如果有人能告诉我哪里出错了,我将不胜感激。