Android libGDX状态更改后没有后台Sprite

时间:2017-04-04 14:41:34

标签: java android libgdx

我想将游戏中的纹理调整为不同的屏幕大小,因此我尝试将ExtendViewport添加到我的viewport中,但每当我尝试更改状态时,都不会加载背景。第一次一切正常,但每当我尝试设置另一个状态时,我都有空白屏幕(我尝试使用相同的State实例来排除代码错误)

STATE

public abstract class State {

protected OrthographicCamera camera;
protected  GameStateManager gsm;
protected Viewport viewport;
public State(GameStateManager gsm) {
    this.gsm = gsm;
    camera = new OrthographicCamera();
    viewport = new ExtendViewport(GAME_SIZE_WIDTH * aspectRatio, GAME_SIZE_HEIGHT, camera);
    viewport.apply();

    camera.position.set(GAME_SIZE_WIDTH / 2, GAME_SIZE_HEIGHT / 2, 0);
     }
public  abstract void handleInput();
public abstract void update(float dt);
public abstract void render (SpriteBatch sb);
public abstract void dispose();
public abstract void resize(int width, int height) ;
}

菜单状态

public class MenuState extends State{


    private Sprite background;
    private Sprite playButton;

    public MenuState(GameStateManager gsm) {
        super(gsm);

        background =new Sprite(new Texture(Gdx.files.internal("back.jpg")));
        background.setSize(GAME_SIZE_WIDTH,GAME_SIZE_HEIGHT);
        background.setPosition(0,0);

        playButton=new Sprite(new Texture("play.png"));
        playButton.setSize(40,30);
        playButton.setPosition(GAME_SIZE_WIDTH/2-playButton.getWidth()/2,GAME_SIZE_HEIGHT/2-playButton.getHeight()/2);
    }



    @Override
    public void render(SpriteBatch sb) {
        sb.setProjectionMatrix(camera.combined);
        sb.begin();
        background.draw(sb);
        playButton.draw(sb);
        sb.end();
    }

    @Override
    public void dispose() {
        playButton.getTexture().dispose();
        background.getTexture().dispose();
    }

    @Override
    public void resize(int width, int height) {
        viewport.update(width,height);
        camera.position.set(GAME_SIZE_WIDTH / 2, GAME_SIZE_HEIGHT / 2, 0);
    }
    @Override
    public void handleInput() {
    if(Gdx.input.justTouched()) {
        gsm.set(new MenuState(gsm));}
    }
    @Override
    public void update(float dt) {
        handleInput();
    }
}

GameStateManager

public class GameStateManager {

private Stack<State> states;

public GameStateManager() {
    states=new Stack<State>();

}

public void push(State state){
    states.push(state);
}
public void pop(){
    states.pop().dispose();
}
public void set(State state){
    states.pop().dispose();
    states.push(state);
}
public void update(float dt){
    states.peek().update(dt);
}

public void render(SpriteBatch sb){
    states.peek().render(sb);
}
public  void resize(int width, int height){
    states.peek().resize(width,height);
}}

1 个答案:

答案 0 :(得分:1)

问题很简单,你没有更新新状态的视口,所以用屏幕宽度和高度更新。

第一次Game Start以这种方式调整State类调用的ApplicationListener方法。

ApplicationListener的{​​{1}} - &gt; resize(,)的{​​{1}} - &gt; GameStateManager的{​​{1}}

之后,resize(,) State或GameStateManager从未调用过。

只需更改State的{​​{1}}方法。

resize(,)