Skip to content

PolygonSprite: setRegion uses mutable Color instance without resetting to vertex values #3722

@bryanwagner

Description

@bryanwagner

In PolygonSprite, getVertexColor should be called inside setRegion before using the mutable Color instance, otherwise the color can be modified by side-effects.

Example:

import com.badlogic.gdx.*;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.graphics.g2d.*;

public class BarebonesBatch extends ApplicationAdapter {
    PolygonSpriteBatch batch;
    Texture texture;
    PolygonRegion region;
    PolygonSprite sprite;

    public void create () {
        batch = new PolygonSpriteBatch();
        texture = new Texture(Gdx.files.internal("data/badlogic.jpg"));
        region = new PolygonRegion(new TextureRegion(texture), new float[] { 0, 0, 0, 100, 100, 100 }, new short[] { 0, 1, 2 });
        sprite = new PolygonSprite(region);
        sprite.setColor(0, 1, 0, 1);
    }

    public void render () {
        // Example:  calling getColor and modifying it causes a side-effect
        if (Gdx.input.isKeyJustPressed(Keys.SPACE)) {
          Color color = sprite.getColor();
          color.set(1, 0, 0, 1);  // only setColor should actually change the color
          //sprite.getVertexColor();  // fix: getVertexColor should be called inside setRegion
          sprite.setRegion(region);
        }
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.begin();
        sprite.draw(batch);
        batch.end();
    }

    public static void main (String[] args) throws Exception {
        new LwjglApplication(new BarebonesBatch());
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions