Search code examples
libgdx

Set shader for single actors


I've started to deal with shaders a bit today and now I'm stuck. I want to apply a shader to certain actors (Images) in a scene2d stage. Is it even possible? I just have a draw method for the whole scene, but not for single actors oder actor-groups.

Outside a scene2d stage I just would do something like this:

batch.setShader(shader);
batch.begin();
batch.draw(Image);
batch.end();
batch.setShader(null);
batch.begin();

How to achieve this in a scene2d environment?


Solution

  • You can change the shader inside the draw method of an Actor and then change it back (the Batch automatically handles flushing when the shader is changed):

    public void draw (Batch batch, float parentAlpha){
        batch.setShader(customShader);
        batch.draw(...);
        batch.setShader(null);
    }
    

    Keep in mind that every time you do this, it will cause the batch to flush. If you have a few dozen actors to draw with the custom shader, you should probably put them in a Group that changes the shader so the batch is only flushed once for the Group:

    //Custom Group:
    public void draw (Batch batch, float parentAlpha){
        batch.setShader(customShader);
        super.draw(batch, parentAlpha);
        batch.setShader(null);
    }