[英]libgdx with scene2d and actor is not displaying the sprite
我正在測試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());
}
}
使用紋理構造精靈並使用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();
}
我也得到了黑屏,直到我明確地將Actor
的高度( setHeight(height)
)和寬度( setWidth(width)
)設置為Sprite
的值。
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);
在draw方法中,你的問題很可能是這一行
batch.draw(sprite, getX(), getY());
我在繪制精靈時看到的代碼是
sprite.draw(batch);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.