6

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.

Luke Vo
  • 17,859
  • 21
  • 105
  • 181
  • 1
    This is the body of the AnimatedSprite `draw` method? It looks right, and looks like the [Image.java](https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Image.java#L118) draw method. Maybe something else? Is this.color used elsewhere? – P.T. Feb 16 '13 at 05:13
  • @P.T. I also looked at `Image` class after had seen your comment. The `Image` class doesn't even reset the batch's color, so I tried remove it in my code. `this.color` is not used elsewhere, and I also give the r g b value instead of entire color instance. However, my entire screen is still tint by a color. – Luke Vo Feb 16 '13 at 09:29
  • @P.T. Thank you for your hint. I found the problem. Because when initializing, I set my Sprite's color to Color.WHITE (of libgdx), so every of my AnimatedSprite are pointing to the same color! – Luke Vo Feb 16 '13 at 09:39
  • I've done that, too. I've added an answer so that others that come along will see this is answered. If you have a chance add a bit of your code that "sets color to black", too. – P.T. Feb 16 '13 at 15:08

2 Answers2

8

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.

P.T.
  • 24,557
  • 7
  • 64
  • 95
1

Rather than use

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

you could use:

batch.setColor(Color.WHITE.tmp());

This will create a temporary copy of the white color and seems slightly cleaner to me.

  • 1
    Color.WHITE.tmp() does not exist in libgdx 1.9.6 – Vokail Mar 05 '18 at 15:36
  • It is .cpy() in latest versions. I believe the best practice is to explicitly set the color before each call (or calls using the same color) to batch.draw(). – Guillaume Nov 20 '19 at 18:43