Search code examples
javaspritelibgdxtintspritebatch

Set SpriteBatch color (for tinting) affects all drawing


I created a AnimatedSprite class, that draw a specific TextureRegion. Sometimes I need a tint color effect, so I set (this.color is a Color field of my AnimatedSprite):

super.draw(batch, parentAlpha);

batch.setColor(this.color);
batch.draw(this.frames[this.currentFrame], x, y, originX, originY, width, height, scaleX, scaleY, rotation)
batch.setColor(Color.WHITE);

However, when I have an AnimatedSprite's color set to black or any color, everything else has that color tint. I even try to flush(), end the batch and begin a new one, etc... but nothing seems to work.

Please help me apply the tint effect correctly. I will appreciate any idea.


Solution

  • Beware shared mutable Color objects! If you do:

    this.color = Color.WHITE;
    

    And then mutate this.color later, you will be mutating Color.WHITE which is generally the wrong thing! :)

    Always make a copy when constructing a Color object that you will mutate:

    this.color = new Color(Color.WHITE);
    

    Many objects in libGDX are mutable like this (whereas similar objects in a regular Java library would be immutable) because libGDX is (rightfully) very concerned about GC overhead.