2013-02-19 77 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);