带有scene2d和actor的libgdx没有显示精灵

Roa*_*tad 3 java libgdx scene2d

我正在测试Libgdx和Scene2d.我希望这个小程序能够显示一个标志,但它只画了一个黑屏.知道我错过了什么吗?

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

ita*_*arb 11

使用纹理构造精灵并使用Gdx.file.internal:

sprite = new Sprite(new Texture(Gdx.files.internal("data/libgdx.png")));
Run Code Online (Sandbox Code Playgroud)

无论如何,如果您只想显示和处理图像,您可能更喜欢使用Image类:

    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);          

        com.badlogic.gdx.scenes.scene2d.ui.Image actor = new com.badlogic.gdx.scenes.scene2d.ui.Image(region);
        stage.addActor(actor);
    }

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

  • 潜入源代码,似乎使用带有Texture的Sprite构造函数也设置了纹理的区域,而仅设置setTexture是不够的,你也需要手动使用setRegion. (3认同)