Roar Skullestad Roar Skullestad - 6 months ago 145
Java Question

libgdx with scene2d and actor is not displaying the sprite

I am testing out Libgdx and Scene2d. I expected this small program to display a logo, but it draws a black screen only. Any idea what am I missing?

public class MyGame implements ApplicationListener {
private Stage stage;

@Override
public void create() {
stage = new Stage(800, 800, false);
Gdx.input.setInputProcessor(stage);
MyActor actor = new MyActor();
stage.addActor(actor);
}

@Override
public void render() {
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
}

@Override
public void dispose() {
stage.dispose();
}

@Override
public void resize(int width, int height) {
stage.setViewport(800, 800, false);
}
}


public class MyActor extends Actor {
Sprite sprite;

public MyActor() {
sprite = new Sprite();
sprite.setTexture(new Texture("data/libgdx.png"));

setWidth(sprite.getWidth());
setHeight(sprite.getHeight());
setBounds(0, 0, getWidth(), getHeight());
setTouchable(Touchable.enabled);
setX(0);
setY(0);
}

@Override
public void draw(SpriteBatch batch, float parentAlpha) {
Color color = getColor();
batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
batch.draw(sprite, getX(), getY());
}
}

Answer

Construct the sprite with the texture and use Gdx.file.internal:

sprite = new Sprite(new Texture(Gdx.files.internal("data/libgdx.png")));

Anyway, if you just want to display and act on images, you might prefer to use Image class:

    private Stage stage;
    private Texture texture;

    @Override
    public void create() {
        stage = new Stage();
        Gdx.input.setInputProcessor(stage);

        texture = new Texture(Gdx.files.internal("data/libgdx.png"));
        TextureRegion region = new TextureRegion(texture, 0, 0, 512, 275);          

        Image actor = new Image(region);
        stage.addActor(actor);
    }

    @Override
    public void render() {
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();
    }
Comments