Setting uniform value of a vertex shader for different sprites in a SpriteBatch

Posted by midasmax on Game Development See other posts from Game Development or by midasmax
Published on 2014-05-22T16:09:16Z Indexed on 2014/08/21 22:28 UTC
Read the original article Hit count: 226

Filed under:
|
|

I'm using libGDX and currently have a simple shader that does a passthrough, except for randomly shifting the vertex positions. This shift is a vec2 uniform that I set within my code's render() loop. It's declared in my vertex shader as uniform vec2 u_random.

I have two different kind of Sprites -- let's called them SpriteA and SpriteB. Both are drawn within the same SpriteBatch's begin()/end() calls. Prior to drawing each sprite in my scene, I check the type of the sprite.

  • If sprite instance of SpriteA: I set the uniform u_random value to Vector2.Zero, meaning that I don't want any vertex changes for it.
  • If sprite instance of SpriteB, I set the uniform u_random to Vector2(MathUtils.random(), MathUtils.random().

The expected behavior was that all the SpriteA objects in my scene won't experience any jittering, while all SpriteB objects would be jittering about their positions.

However, what I'm experiencing is that both SpriteA and SpriteB are jittering, leading me to believe that the u_random uniform is not actually being set per Sprite, and being applied to all sprites. What is the reason for this? And how can I fix this such that the vertex shader correctly accepts the uniform value set to affect each sprite individually?

passthrough.vsh

attribute vec4 a_color;
attribute vec3 a_position;
attribute vec2 a_texCoord0;

uniform mat4 u_projTrans;
uniform vec2 u_random;

varying vec4 v_color;
varying vec2 v_texCoord;

void main() {

    v_color = a_color;
    v_texCoord = a_texCoord0;

    vec3 temp_position = vec3( a_position.x + u_random.x, a_position.y + u_random.y, a_position.z);

    gl_Position = u_projTrans * vec4(temp_position, 1.0);

}

Java Code

this.batch.begin();
this.batch.setShader(shader);

for (Sprite sprite : sprites)
{
    Vector2 v = Vector2.Zero;
    if (sprite instanceof SpriteB)
    {
        v.x = MathUtils.random(-1, 1);
        v.y = MathUtils.random(-1, 1);
    }

    shader.setUniformf("u_random", v);

    sprite.draw(this.batch);
}

this.batch.end();

© Game Development or respective owner

Related posts about libgdx

Related posts about glsl