I'm programming a 2D game libgdx. I'm using a SpriteBatch of course to draw some Sprites. Now I wanted to use multiple ShaderPrograms with the SpriteBatch, but unfortunately you can set only one `ShaderProgram at a time. For example, I wanted to draw the whole scene with a specific color and wanted to add a parallax effect to some sprites by manipulating the texCoords in the shader. I know in native OpenGL you can just enable as much shaders as you want before your draw call. But it seems that in libgdx it is not possible.

  • \$\begingroup\$ Why don't you just combine the shaders? \$\endgroup\$
    – Charanor
    Jul 21 '17 at 16:57

You can first render your scene to a texture with the first shader, then render the texture with the second shader. This will apply both shaders to your scene. You render to texture using a FrameBuffer.

SpriteBatch batch = new SpriteBatch();
FrameBuffer fbo = new FrameBuffer(Format.RGBA8888, width, height, hasDepth);
TextureRegion fboTexture = new TextureRegion(fbo.getColorBufferTexture());
fboTexture.flip(false, true); // Have to flip on Y axis

public void render(float delta) {
    // Draw scene to texture
    // If you're having issues with the drawing try doing glClear right after fbo.begin().
    // Draw here

    // Draw scene to screen
    // Draw here

The much simpler way would be to just combine the two shaders into one shader, though.

  • 1
    \$\begingroup\$ +1 for the answer, however the last sentence may be dubious if you need to apply the second shader selectively for some sprites \$\endgroup\$
    – comodoro
    Jun 23 '18 at 12:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.