libgdx与scene2d和actor一起使用时无法显示精灵。

3

我正在测试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());
    }
}

batch.setColor()中将alpha(第四个参数)强制设置为1.0f,看看是否有帮助。我怀疑默认颜色全部为零。 - P.T.
改为batch.setColor(color.r, color.g, color.b, 1.0f),但结果相同。 - Roar Skullestad
4个回答

11

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

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

无论如何,如果你只想显示和处理图片,你可能更喜欢使用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();
    }

1
为什么 setTexture(new Texture(Gdx.files.internal("data/libgdx.png"))); 不起作用? - Roar Skullestad
3
深入查看源代码后发现,使用 Sprite 的构造函数并传入一个 Texture 对象可以设置纹理的区域,而仅仅使用 setTexture 是不够的,你还需要手动使用 setRegion。 - itamarb

3

我之前也遇到了黑屏的问题,直到我明确地将Actor的高度(setHeight(height))和宽度(setWidth(width))设置为Sprite的值才解决了这个问题。


0

你的问题很可能在draw方法中的这一行代码

batch.draw(sprite, getX(), getY());

我在绘制精灵时看到的代码是
sprite.draw(batch);

0
tex = new Texture(Gdx.files.internal("happy.png"));
Image happy = new Image(tex);    
/* happy.setBounds(happy.getX(), happy.getY(), happy.getWidth(), happy.getHeight());  not needed if using full image               */    
stage.addActor(happy);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接