2013-02-19 33 views
3

我测试了Libgdx和Scene2d。我期望这个小程序显示一个标志,但它只画黑屏。任何想法我错过了什么?libgdx与scene2d和actor不显示sprite

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()); 
    } 
} 
+0

在'batch.setColor()'中强制alpha(第四个参数)为1.0f,看看是否有帮助。我怀疑默认颜色是全零。 – 2013-02-20 06:34:32

+0

更改为'batch.setColor(color.r,color.g,color.b,1.0f)',但结果相同。 – 2013-02-20 07:48:30

回答

10

构建精灵与质感和使用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(新纹理(Gdx.files.internal(“data/libgdx.png”)));'工作? – 2013-02-20 09:31:25

+3

潜入源代码中,似乎使用具有纹理的Sprite的构造函数也设置纹理的区域,而仅设置setTexture是不够的,您还需要手动使用setRegion。 – itamarb 2013-02-20 09:34:43

3

我得到一个黑色的屏幕太大,直到我明确设置Actor的高度(setHeight(height))和宽度(setWidth(width))至Sprite的值。

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