Android游戏冻结半秒

时间:2014-04-11 15:21:19

标签: java android libgdx freeze

我是初学程序员,我正在尝试使用LibGDX为Android制作游戏。我不明白为什么它在整个游戏中停留不到半秒(在桌面上运行),如果我在手机或模拟器上运行它,冻结时间超过半秒。这是代码:

    @Override
public void show() {
       stage = new Stage(physicWidth, physicHeight, true);
       gun = new ArrayList<Guns>();
       buildingAtlas = new TextureAtlas(Gdx.files.internal("ui/cladiri.pack"));
   buildingSkin = new Skin(buildingAtlas);
   building1 = new ImageButton(buildingSkin.getDrawable("cladire1"));
   building2 = new ImageButton(buildingSkin.getDrawable("cladire2"));

       table = new Table();
   table.setBounds(0, tileH * 4, tileW * 6, tileH);
   table.left();
   table.add(building1).width((float) (tileW * 0.8)).height((float) (tileH * 0.7));
   table.add(building2).width((float) (tileW * 0.8)).height((float) (tileH * 0.7));
       stage.addActor(table);
       Gdx.input.setInputProcessor(stage);

       building1.addListener(new InputListener(){
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            gun.add(new Guns(selectedTile.x, selectedTile.y));
            return true;
        }
    });
    building2.addListener(new InputListener(){
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("Touch on Building 2");
            return true;
        }
    });

    }


    @Override
public void render(float delta) {
    batch.begin();
    for(int i = 0; i < gun.size(); i++){
      gun.get(i).render(batch, tileW, tileH);
    }
    batch.end();
    }

枪支课程是:

public Guns(float x, float y) {
    this.y = y;
    this.x = x;
    gunTexture = new Texture(Gdx.files.internal("img/gunTest1.png"));
    TextureRegion[][] tmp = TextureRegion.split(gunTexture, gunTexture.getWidth() / 
            COLS, gunTexture.getHeight() / ROWS);
    gunFrames = new TextureRegion[COLS * ROWS];
    int index = 0;
    for (int i = 0; i < ROWS; i++) {
            for (int j = 0; j < COLS; j++) {
                    cladireFrames[index++] = tmp[i][j];
            }
    }
    gunAnimation = new Animation(0.1f, gunFrames);
    stateTime = 0f;

    bounds = new Rectangle();
}

public void update(){
    stateTime += Gdx.graphics.getDeltaTime();
    curGunFrame = gunAnimation.getKeyFrame(stateTime, true);
}

public void render(SpriteBatch batch, float w, float h){
    batch.draw(getCurGunFrame(), x, y, w, h); 
}

如果触摸执行&#34; System.out.println&#34;的building2按钮;游戏并没有冻结,但是在建筑物1上添加一个新的枪然后它会冻结。

我发布的代码是简化的,只是与我的问题有关。

1 个答案:

答案 0 :(得分:1)

看起来这些行之一会导致您的问题:

gunTexture = new Texture(Gdx.files.internal("img/gunTest1.png"));
TextureRegion[][] tmp = TextureRegion.split(gunTexture, gunTexture.getWidth() / 
        COLS, gunTexture.getHeight() / ROWS);

纹理加载通常是一项昂贵的操作,然后在加载后进行操作,其中一个或两个操作几乎肯定会导致您遇到的延迟。我相信解决这个问题的标准机制是在对象之间共享纹理并在关卡开始时加载纹理,而不是在运行时加载。

您的游戏不应让您的Gun类在创建时创建新纹理,而应将纹理与x和y变量一起传递给构造函数。

桌面和手机之间经历不同延迟时间的原因很可能是因为您的桌面功能更强大。