I see you are unfamiliar with the Scene2D
provided by LibGDX. You will find this article more than helpful. [url=https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/scenes/scene2d/Actor.java]Actor.java[/url]
already has all of the properties you wish to use except Texture
/TextureRegion
.
Of course. Here is the modified version of MySpriteActor.java
.
public abstract class MySpriteActor extends Actor {
private Texture texture;
private boolean flipX, flipY;
public MySpriteActor(float x, float y, Texture texture) {
this.texture = texture;
this.setPosition(x, y);
this.setSize(texture.getWidth(), texture.getHeight()); // Initial size is 0f, 0f - nothing would get drawn.
this.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
MySpriteActor.this.clicked(event, event.getButton(), x, y);
}
});
}
protected abstract void clicked(InputEvent event, int button, float x, float y);
@Override
public void draw(Batch batch, float parentAlpha) {
Color color = getColor();
// Set this so texture is tinted with the color you can change with setColor() method.
// Plus, if the action is Actions.fadeOut or Actions.fadeIn, make the actor change alpha/visibility.
batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
// Render the texture correctly even when it changes position, rotation, size, scale, etc.
// Also useful if you're going to use Actions.
if (texture != null) {
batch.draw(
texture,
getX(), getY(), getOriginX(), getOriginY(),
getWidth(), getHeight(), getScaleX(), getScaleY(),
getRotation(),
// It's like TextureRegion, what area of the Texture to draw.
// Well, this is going to draw whole texture.
0, 0, texture.getWidth(), texture.getHeight(),
flipX, flipY
);
}
}
}
And then you would do something like this in your screen:
public class Example implements Screen {
private Stage stage;
private Texture texture;
private MySpriteActor actor;
@Override
public void show() {
stage = new Stage();
texture = new Texture(Gdx.files.internal("badlogic.jpg"));
actor = new MySpriteActor(0f, 0f, texture) {
@Override
protected void clicked(InputEvent event, int button, float x, float y) {
// ...
}
};
stage.addActor(actor);
}
@Override
public void render(float delta) {
stage.act(delta); // Needs to be called for updating and input events.
stage.draw(); // And needs to render.
}
@Override
public void hide() {
dispose();
}
@Override
public void dispose() {
stage.dispose();
texture.dispose();
}
@Override
public void resize(int width, int height) {
}
@Override
public void pause() {
}
@Override
public void resume() {
}
}