简体   繁体   English

如何在 libgdx 中创建非常简单的暂停/恢复游戏

[英]How to create very simple pause/resume game in libgdx

i am newbie for libgdx, How to create very simple pause/resume game in libgdx??我是 libgdx 的新手,如何在 libgdx 中创建非常简单的暂停/恢复游戏?

I'm trying to implement simple game using libgdx.我正在尝试使用 libgdx 实现简单的游戏。 I have want to create pause the game but don't know how to pause and resume game based on user input.Kindly suggest idea as well as some practical code to implement the same.I am using simple game code demonstrated in libgdx library.我想创建暂停游戏,但不知道如何根据用户输入暂停和恢复游戏。请提出想法以及一些实用代码来实现相同。我正在使用 libgdx 库中演示的简单游戏代码。 Thank you.谢谢你。

public class MyGdxGame extends ApplicationAdapter {
    SpriteBatch batch;
    Texture img;
    float x;
    float y;

@Override
public void create () {
    batch = new SpriteBatch();
    img = new Texture("badlogic.jpg");
}

@Override
public void render () {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    x= x+4;

    if(Gdx.input.isKeyPressed(Input.Keys.P)){
      // pause
        
    }

    batch.begin();
    batch.draw(img, x, y);
    batch.end();
}

@Override
public void dispose () {
    batch.dispose();
    img.dispose();
}

} }

Press P key to press the game按P键按游戏

if(Gdx.input.isKeyPressed(Input.Keys.P)){
      // if(game.pause()){
             game.resume();
          }else{
           game.pause();
             }

    }

any idea???任何想法??? thanks谢谢

Your render method is called repeatable and what "paused" means is up to you.您的渲染方法称为可重复的,“暂停”的含义取决于您。 You have to implement your logic that handles "paused" state because that doesn't mean anything to libGDX.您必须实现处理“暂停”state 的逻辑,因为这对 libGDX 没有任何意义。

If you want everything to freeze when game is paused but still to be drawn best way is (IMHO) to fully separate drawing from calculating (movements and stuff).如果您希望在游戏暂停时一切都冻结但仍要绘制,最好的方法是(恕我直言)将绘制与计算(动作和东西)完全分开。 So ie when your render method is called you will call your drawing method once (to draw the graphics) but you will also calculate how many times your calculation method should be call (to have same game speed independently on frame rate) and call it that many times.因此,即当您的渲染方法被调用时,您将调用您的绘图方法一次(绘制图形),但您还将计算您的计算方法应该调用多少次(在帧速率上具有相同的游戏速度)并调用它很多次。

Then when your game is paused you will just skip calling your calculation method and call only drawing method.然后,当您的游戏暂停时,您将跳过调用计算方法而仅调用绘图方法。 So nothing will move and until you end your pause the same graphics will be drawn.所以什么都不会移动,直到您结束暂停,将绘制相同的图形。

And to keep paused state you can have some boolean variable.为了保持暂停 state 你可以有一些 boolean 变量。 Every time p key is pressed you should invert it, like:每次按下 p 键时,您都应该反转它,例如:

if(Gdx.input.isKeyPressed(Input.Keys.P)){
    paused = !paused;
}

or something (as @Tenfour04 suggested).或其他东西(如@Tenfour04 建议的那样)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM