Reputation: 1221
I have this class:
public class MyActor extends Actor{
TextureRegion region;
public MyActor(TextureRegion region)
{
this.region = region;
}
@Override
public void draw(Batch batch, float parentAlpha) {
super.draw(batch, parentAlpha);
batch.draw(region, 0, 0);
}
}
And I make use of it here like this:
public class MyGame implements ApplicationListener {
Stage stage;
MyActor myActor;
@Override
public void create() {
stage = new Stage(0, 0, false);
myActor = new MyActor(new TextureRegion(new Texture(
Gdx.files.internal("texture.png"))));
myActor.setPosition(200, 50);
stage.addActor(myActor);
}
@Override
public void render() {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
}
}
In the MyActor
class I set the position of the actor to (0, 0)
. I just used this as some kind of default as I want to be able to change its position before it's actually drawn on the stage. The reason is I have a few MyActor
objects and I want to draw them all on the stage but at different positions.
So I did myActor.setPosition(200, 50);
, but it didn't work.
My question: How can I draw myActor
on the stage with position other than what is set in draw(Batch, float)
?
Upvotes: 0
Views: 735
Reputation: 9823
Instead of extending Actor
you could extend Image
, which is a subclass of Actor
. Image
allready holds a Drawable
(you can use your TextureRegion
in the constructor of TextureRegionDrawable
). Then in your Image
-subclass you can override draw(Batch batch, float parentAlpha)
, do some controlls if necessary and call suoer.draw(batch, parentAlpha)
and there your Actor
will be drawn at the right position
, rotation
, scale
...
EDIT: Image
is a subclass of Widget
. Widget
itself extends Actor
.
From LibGDX Api:
Displays a Drawable, scaled various way within the widgets bounds. The preferred size is the min size of the drawable. Only when using a TextureRegionDrawable will the actor's scale, rotation, and origin be used when drawing.
So if you use a TextureRegionDrawable it will also handle the rotation, scale and origin you set to your Actor
, if you need that. It has everything that Actor
class has and MORE
Another EDIT: As you said you have to store other data you can simply have your MyActor extends Image
. In your MyActor
you can store all the Data you need, but you don't need to store the Image anymore and you don't have to take care about drawing anymore. So this is just a suggestion.
Upvotes: 0
Reputation: 19796
public void draw(Batch batch, float parentAlpha) {
super.draw(batch, parentAlpha);
batch.draw(region, 0, 0);
}
Remove the super.draw
call here. Right now it shouldn't do anything, if it would do anything, it will probably cause problems.
Furthermore, you complained, that your actor position is not used. That's because you didn't use it.
Try something like this instead:
public void draw(Batch batch, float parentAlpha) {
batch.draw(region, getX(), getY());
}
Upvotes: 2