简体   繁体   中英

Unconsistent color gradient drawing rectangles/sprites in libgdx

I'm trying to draw sprites with color gradients using a SpriteBatcher and setting manually the vertex colors to achieve some kind of basic illumination effect without shaders, but I noticed a weird effect in the gradients when only one of the vertex color is different.

It depends on the position of the vertex. If the different color is on the bottom-left or the top-right there's no problem, but in the other two cases there's a weird gradient effect.

To explain better the situation, here's an image.

结果

I generated the top row of squares with the following code:

shapeRenderer.begin(ShapeType.Filled);
Color c1 = new Color(1,1,1,1);
Color c2 = new Color(1,0,0,1);
shapeRenderer.rect(100f, 100f, 30f, 30f, c2, c1, c1, c1);
shapeRenderer.rect(150f, 100f, 30f, 30f, c1, c2, c1, c1);
shapeRenderer.rect(200f, 100f, 30f, 30f, c1, c1, c2, c1);
shapeRenderer.rect(250f, 100f, 30f, 30f, c1, c1, c1, c2);
shapeRenderer.end();

This code is generated with a ShapeRenderer, but I get the same result if I do it with a SpriteBatch.

I imagine it's related to the way a rect is drawn internally (based on 2 triangles) but, is there any way to achieve the same result in all the cases? (as the 3rd row of the image)

Something like a different GL draw mode or whatever... ?

OK, so the thing is, that the drawing depends on the order of the triangles. If the gradient goes from one vertex of the triangle through its angle bisector there's no problem, but if the color gradient goes along its side, the result is like the top-1 and top-3 squares.

This is due (I think) to the fact a rectangle drawn like

1-2
| |
4-3

Is actually drawn with two triangles like

1-2       1
 \|  and  |\
  3       4-3

So, in this order, if the different color is in the vertex 1 or 3, the resulting gradient is weird.

What we can do in this cases is change the order of the vertexes (not its coordinates) to be drawn like this

2-3      2-3       3
| |  =>  |/   +   /|
1-4      1       1-4

It works just fine as we can see here:

结果

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM