How to pause the game in Screen libgdx? - java

Sorry for my question , but i am stuck. I am new in develop game with lib gdx and don`t judge me strictly.
I have my game activity:
public class MyGame extends Game {
MenuScreen menu;
SplashScreen splash;
DefendScreen def;
#Override
public void create() {
// Gdx.app.log("LogGame", "MyGame create");
menu = new MenuScreen(this);
splash = new SplashScreen(this);
def = new DefendScreen(this);
setScreen(splash);
}
#Override
public void resize(int width, int height) {
}
#Override
public void render() {
super.render();
}
#Override
public void pause() {
super.pause();
}
#Override
public void resume() {
super.resume();
}
#Override
public void dispose() {
}
}
I have two screens :
public class MenuScreen implements Screen, InputProcessor {
public MenuScreen(final MyGame gam) {
game = gam;
cam = new OrthographicCamera();
cam.setToOrtho(false, 800, 480);
w = Gdx.graphics.getWidth();
h = Gdx.graphics.getHeight();
defScreen = new DefendScreen(game);
spriteBatch = new SpriteBatch();
stage = new Stage();
}
#Override
public void dispose() {
Gdx.app.log("LogGame", "splashs dispose");
Gdx.input.setInputProcessor(null);
try {
spriteBatch.dispose();
stage.dispose();
font12.dispose();
} catch (Exception e) {
}
}
#Override
public void hide() {
// TODO Auto-generated method stub
}
#Override
public void pause() {
}
#Override
public void render(float arg0) {
SetCamera(CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2f);
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act(); // update all actors
stage.draw();
}
#Override
public void resize(int arg0, int arg1) {
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void show() {
stage.addActor(new WorldMenu(new Texture(Gdx.files
.internal("images/bg/pause_back.png"))));
Gdx.input.setInputProcessor(stage);
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(
Gdx.files.internal("font/trebuchet_ms.ttf"));
FreeTypeFontParameter parameter = new FreeTypeFontParameter();
parameter.size = 25;
font12 = generator.generateFont(parameter);
generator.dispose();
DrawLeftMeu();
DrawRightMeu();
DrawSetingsMenu();
}}
And game screen where i have pause button:
public class DefendScreen implements Screen, InputProcessor {
public DefendScreen(final MyGame gam) {
game = gam;
cam = new OrthographicCamera();
cam.setToOrtho(false, 800, 480);
startTime = TimeUtils.millis();
spriteBatch = new SpriteBatch();
stage = new Stage();
w = Gdx.graphics.getWidth();
h = Gdx.graphics.getHeight();
}
#Override
public void dispose() {
Gdx.app.log("LogGame", "defend dispose");
try {
combo0.dispose();
combo1.dispose();
combo2.dispose();
good0.dispose();
good1.dispose();
bad0.dispose();
bad1.dispose();
bad2.dispose();
bad3.dispose();
bad4.dispose();
music.dispose();
music.stop();
spriteBatch.dispose();
font.dispose();
pbar.dispose();
scores.dispose();
} catch (Exception e) {
}
}
#Override
public void hide() {
}
#Override
public void pause() {
// this.state = State.PAUSE;
}
#Override
public void render(float delta) {
SetCamera(CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2f);
switch (state) {
case RUN:
RunGame();
break;
case PAUSE:
// do stuff here
break;
case RESUME:
break;
default:
break;
}
}
#Override
public void resize(int arg0, int arg1) {
}
#Override
public void resume() {
this.state = State.RESUME;
}
#Override
public void show() {
regions = new ArrayList<Integer>();
addRegions();
initSounds();
speedgame = speedgameEasy;
stage.addActor(worldActor);
stage.addActor(pauseActor);
startTime = TimeUtils.millis();
stage.addListener(clickList);
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(
Gdx.files.internal("font/trebuchet_ms.ttf"));
FreeTypeFontParameter parameter = new FreeTypeFontParameter();
parameter.size = 25;
font = generator.generateFont(parameter);
generator.dispose();
pbar = new Texture(Gdx.files.internal("images/bg/line_indicator.png"));
scores = new Texture(
Gdx.files.internal("images/game_images/scorebox.png"));
Gdx.input.setInputProcessor(stage);
Gdx.input.setCatchBackKey(true);
}}
And my main questions !!!
--> what i must do that on pause action i can freeze the game action and call menu screen (whish have button resume)?
--> what i mus do in resume onclick to show game action resume?
on stackoverflow an other forums i find some explains about my question, which means to implement in resume some switch case with choices of game state, but i am do not understand how its realize in my code.
Thanks everyone.

In your game screen you should have a button (an actor added to the stage) which implements a ClickListener that calls either pause() or resume() depending on the current state of the game.
It should look something like this:
pauseButton.addListener(new ClickListener() {
public void clicked(InputEvent evt, float x, float y) {
if (!paused) Gdx.app.getApplicationListener().pause();
else Gdx.app.getApplicationListener().resume();
}
});
Where paused is a boolean variable in your game screen class.
In my opinion this is the easiest way to do this.

Related

Libgdx, button onclick event crashes

I'm trying to create an android game using libgdx with a Titlescreen, you just press start and your game startes. However I'm having difficulty trying to get these buttons to work. The title-screen works, but as soon as I press 'start game' the game crashes with the error:
Exception in thread "LWJGL Application" java.lang.NullPointerException
at com.dinab.onepiecev2.TitleScreen$1.clicked(TitleScreen.java:47) at
com.badlogic.gdx.scenes.scene2d.utils.ClickListener.touchUp(ClickListener.java:88)
at
com.badlogic.gdx.scenes.scene2d.InputListener.handle(InputListener.java:59)
at com.badlogic.gdx.scenes.scene2d.Stage.touchUp(Stage.java:351) at
com.badlogic.gdx.backends.lwjgl.LwjglInput.processEvents(LwjglInput.java:360)
at
com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:221)
at
com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:128)
I don't understand what I'm doing wrong and whether the problem is in my TitleScreen.java or in my GameScreen.java
These are my codes:
Main class
public class Onepiecev2 extends Game {
static public Skin gameSkin;
public void create () {
gameSkin = new Skin(Gdx.files.internal("skin/glassy-ui.json"));
this.setScreen(new TitleScreen(this));
}
public void render () {
super.render();
}
public void dispose () {
}
}
TitleScreen
public class TitleScreen implements Screen {
Stage stage;
Game game;
SpriteBatch batch;
Texture img;
TextureRegion mainBackground;
public TitleScreen(Game aGame){
batch = new SpriteBatch();
img = new Texture("start_screen.jpg");
mainBackground = new TextureRegion(img, 0, 0, 1920, 1080);
stage = new Stage(new ScreenViewport());
Gdx.input.setInputProcessor(stage);
Skin mySkin = new Skin(Gdx.files.internal("skin/glassy-ui.json"));
Button start_btn = new TextButton("START GAME", mySkin);
start_btn.setSize(Constantes.screenWidth/4, Constantes.screenHeight/12);
start_btn.setPosition(Constantes.col_width*3,Constantes.row_height/3);
start_btn.addListener( new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
game.setScreen( new GameScreen(game) );
}
} );
stage.addActor(start_btn);
}
#Override
public void show() {
Gdx.input.setInputProcessor(stage);
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(mainBackground, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.end();
stage.act();
stage.draw();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
stage.dispose();
batch.dispose();
img.dispose();
}
}
GameScreen
public class GameScreen implements Screen {
Stage stage;
Game game;
SpriteBatch batch;
Texture img;
TextureRegion mainBackground;
public GameScreen(Game aGame){
batch = new SpriteBatch();
img = new Texture("start_screen.jpg");
mainBackground = new TextureRegion(img, 0, 0, 1920, 1080);
stage = new Stage(new ScreenViewport());
Gdx.input.setInputProcessor(stage);
Skin mySkin = new Skin(Gdx.files.internal("skin/glassy-ui.json"));
Button start_btn = new TextButton("GO BACK", mySkin);
start_btn.setSize(Constantes.screenWidth/4, Constantes.screenHeight/12);
start_btn.setPosition(Constantes.col_width*3,Constantes.row_height/3);
start_btn.addListener( new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
game.setScreen( new TitleScreen(game));
}
} );
stage.addActor(start_btn);
}
#Override
public void show() {
Gdx.input.setInputProcessor(stage);
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(mainBackground, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.end();
stage.act();
stage.draw();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
stage.dispose();
batch.dispose();
img.dispose();
}
}
From the crash log, it looks like the problem is in your TitleScreen where you are adding a click listener. I am referring to the following line.
game.setScreen(new GameScreen(game));
Looks like the game object is not initialized before and hence you are getting a NullPointerException.

libGDX manager.update() blocking animations

I successfully implemented a gifdecoder in my project and wrote a gifloader for it to use it with the assetmanager. I am able to load the gif in the assetmanager and I am also able to draw it. But everytime I try to load gifs in my assetmanager with manager.update() I can not draw animations anymore, only non animated textures.
Here is my code I hope somebody has an idea
public class Load implements Screen {
private SpriteBatch batch;
private Animation<TextureRegion> loadingAnimation;
private TextureAtlas atlasLoading = new TextureAtlas(Gdx.files.internal("atlas/loadingAnimation.atlas"));
float stateTime;
MainExecute lr;
public FileHandleResolver resolver = new InternalFileHandleResolver();
public AssetManager manager = new AssetManager();
private final Animation animation = GifDecoder.loadGIFAnimation(Animation.PlayMode.NORMAL, Gdx.files.internal("data/loading.gif").read());
public Load(MainExecute lr){
this.lr = lr;
}
public Texture Bg1;
#Override
public void show() {
Bg1 = new Texture(Gdx.files.internal("bggamescreen.png"));
batch = new SpriteBatch();
manager.setLoader(GIF.class,new Gifloader(resolver));
manager.load("data/BackgroundAnim.gif",GIF.class);
stateTime = 0f;
}
#Override
public void render(float delta) {
if (manager.update())
{
lr.setScreen(new MainMenu(lr));
}
stateTime += delta;
// loadingAnimation = new Animation<TextureRegion>(0.5f, atlasLoading.findRegions("loading"),Animation.PlayMode.LOOP);
TextureRegion currentFrame = (TextureRegion) animation.getKeyFrame(stateTime, true);
batch.begin();
batch.draw(Bg1,0,0,Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
batch.draw(currentFrame, 0, 0, 200, 200);
batch.end();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
}
}
Strange code, you are drawing animation before it finish loading. You need to waiting to load your animation, try smth like this.
if (manager.update())
{
loadingAnimation = new Animation<TextureRegion>(0.5f, atlasLoading.findRegions("loading"),Animation.PlayMode.LOOP);
TextureRegion currentFrame = (TextureRegion) animation.getKeyFrame(stateTime, true);
lr.setScreen(new MainMenu(lr));
}

libgdx click area above target

I'm trying to make a simple main menu with clickable play and exit labels, but clickable area is always above labels. To click "play" label I need to click about 20 pixels above it.
How can I align clickable area with labels?
There is my MainMenuButton class
public class MainMenuButtons {
private MainGame game;
private Stage stage;
private Viewport gameViewport;
private Label mainGameLabel, playLabel, exitLabel;
public MainMenuButtons(MainGame game) {
this.game = game;
gameViewport = new FillViewport(GameInfo.WIDTH, GameInfo.HEIGHT, new OrthographicCamera());
stage = new Stage(gameViewport, game.getBatch());
Gdx.input.setInputProcessor(stage);
createLabelsAndButtons();
addAllListeners();
Table menuTable = new Table();
menuTable.center().center();
menuTable.setFillParent(true);
menuTable.add(playLabel);
menuTable.row();
menuTable.add(exitLabel).padTop(40);
Table gameTitle = new Table();
gameTitle.center().top();
gameTitle.setFillParent(true);
gameTitle.add(mainGameLabel).padTop(40);
menuTable.debug();
stage.addActor(menuTable);
stage.addActor(gameTitle);
}
void createLabelsAndButtons() {
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("Fonts/PressStart2P.ttf"));
FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
parameter.size = 45;
BitmapFont font = generator.generateFont(parameter);
mainGameLabel = new Label("Road Racer", new Label.LabelStyle(font, Color.WHITE));
parameter.size = 25;
font = generator.generateFont(parameter);
playLabel = new Label("Play", new Label.LabelStyle(font, Color.WHITE));
exitLabel = new Label("Exit", new Label.LabelStyle(font, Color.WHITE));
}
void addAllListeners() {
playLabel.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y) {
super.clicked(event, x, y);
System.out.println("Play label clicked " + y);
// game.setScreen(new GamePlay(game));
}
});
exitLabel.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y) {
super.clicked(event, x, y);
System.out.println("Exit label clicked " + y);
// Gdx.app.exit();
}
});
}
public Stage getStage() {
return this.stage;
}
}
And I call it in the MainMenu class
/**
* Created by vladk on 24/09/16.
*/
public class MainMenu implements Screen {
private MainGame game;
private OrthographicCamera mainCamera;
private Viewport gameViewport;
private MainMenuButtons btns;
public MainMenu(MainGame game) {
this.game = game;
mainCamera = new OrthographicCamera();
mainCamera.setToOrtho(false, GameInfo.WIDTH, GameInfo.HEIGHT);
mainCamera.position.set(GameInfo.WIDTH / 2f, GameInfo.HEIGHT / 2f, 0);
gameViewport = new StretchViewport(GameInfo.WIDTH, GameInfo.HEIGHT, mainCamera);
// background ??
// buttons
btns = new MainMenuButtons(game);
}
#Override
public void show() {
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// game.getBatch().begin();
// game.getBatch().end();
game.getBatch().setProjectionMatrix(btns.getStage().getCamera().combined);
btns.getStage().draw();
btns.getStage().act();
}
#Override
public void resize(int width, int height) {
gameViewport.update(width, height);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
// bg
// buttons
btns.getStage().dispose();
}
}
I found a solution. I needed to update view port for the MainMenuButtons, so I created a new method
// in the MainMenuButtons class
public void viewportUpdate(int width, int height) {
gameViewport.update(width, height);
}
and call if from the MainMenu class
#Override
public void resize(int width, int height) {
gameViewport.update(width, height);
btns.viewportUpdate(width, height);
}

libgdx rendering srite over another causes background sprite to disapear

image of problem http://imgur.com/ZNpHiiu so I succesfully rendered a background for my game , now i tried to render some sprites on top of it and screen gets all messed up big Blue L.
code main
public class WizardGame extends Game {
public static final String TITLE = "Are you a bad enough wizard to save the princess?!", VERISION = "0.0.0.0.PREALPHA";
PlayTest pt = new PlayTest();
private FPSLogger fps;
public void create() {
Gdx.gl20.glClearColor(0, 0, 0, 1);
Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT);
fps = new FPSLogger();
fps.log();
pt.create();
}
public void dispose() {
super.dispose();
}
public void render() {
super.render();
pt.render();
}
public void resize(int width, int height) {
super.resize(width, height);
}
public void pause() {
super.pause();
}
public void resume() {
super.resume();
}
}
playtest code
public class PlayTest implements Screen {
private TextureAtlas atlas;
private AtlasRegion floor;
private SpriteBatch batch;
private OrthographicCamera camera;
private Sprite background;
private BitmapFont font;
private String fps;
Blocks block = new Blocks();
public void render() {
Gdx.gl20.glClearColor(0, 0, 05, 1);
Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
background.setBounds(0, 0, 720, 1280);
background.draw(batch);
block.renderBlocks();
batch.end();
}
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
public void show() {
}
public void hide() {
}
public void pause() {
}
public void resume() {
}
public void dispose() {
atlas.dispose();
batch.dispose();
}
public void create() {
atlas = new TextureAtlas(Gdx.files.internal("data/wizardpack.pack"));
floor = atlas.findRegion("Backfloor");
background = new Sprite(floor);
batch = new SpriteBatch();
font = new BitmapFont(Gdx.files.internal("data/magicdebug48.fnt"));
block.create();
}
#Override
public void render(float delta) {
// TODO Auto-generated method stub
}
}
block code
public class Blocks extends Game {
private TextureAtlas atlas;
private SpriteBatch batch;
private AtlasRegion sword,shield,staff,fireball,iceball;
private Sprite sprSword,sprShield,sprStaff,sprFireball,sprIceball;
#Override
public void create() {
atlas = new TextureAtlas(Gdx.files.internal("data/wizardpack.pack"));
batch = new SpriteBatch();
sword = atlas.findRegion("Sword");
shield = atlas.findRegion("Shield");
staff = atlas.findRegion("Staff");
fireball = atlas.findRegion("flame");
iceball = atlas.findRegion("icespell");
sprSword = new Sprite(sword);
sprShield = new Sprite(shield);
sprStaff = new Sprite(staff);
sprFireball = new Sprite(fireball);
sprIceball = new Sprite(iceball);
}
public void renderBlocks(){
Gdx.gl20.glClearColor(0, 0, 05, 1);
Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(sword, 0, 0, 0, 0, 32, 32, 1, 1, 0);
//sprShield.setBounds(15, 15, 32, 32);
// sprShield.draw(batch);
batch.end();
}
public void dispose(){
atlas.dispose();
batch.dispose();
}
}
I fixed it :D the call to renderBlocks has to be after the end of batch.

LibGDX Actor draw override

I am trying to override my Player class that extends Actor draw method but I am receiving an error saying
The method draw(SpriteBatch, float) of type Player must override or
implement a supertype method
Why can I not override the default draw method from the class Actor? Here is my code from the Player class.
public class Player extends Actor {
#Override
public void draw(SpriteBatch batch, float parentAlpha) {
Gdx.app.log(getName(), "Drawing player");
}
public Player() {
setName("mainPlayer");
playerBounds = new Rectangle(100, 100, 32, 32);
}
}
Here is my code from the class with the Stage that is being drawn.
public class Mainscreen implements Screen {
// Class TAG
private static final String TAG = "Main Screen";
// Screen Variable(s)
private Awakening g;
private SpriteBatch sprBatch;
private OrthographicCamera gameCamera;
private Player mainPlayer;
// Screen Stage(s)
private sMain sMain;
#Override
public void dispose() {
sprBatch.dispose();
sMain.dispose();
}
#Override
public void hide() {
g.inputController.removeProcessor(sMain);
dispose();
}
public Mainscreen(Awakening game){
g = game;
sMain = new sMain(g, g.configMgr.getWidth(), g.configMgr.getHeight(), true);
gameCamera = new OrthographicCamera();
gameCamera.setToOrtho(false, sMain.getWidth(), sMain.getHeight());
mainPlayer = new Player(g, gameCamera);
g.setPlayer(mainPlayer);
sprBatch = new SpriteBatch();
g.mapMgr.setMap(g, gameCamera, "TestMap", mainPlayer);
sMain.addActor(mainPlayer);
}
#Override
public void pause() {g.togglePause(true);g.debugOut(TAG, "pause()");}
#Override
public void render(float delta) {
if(!g.isPaused()){
sMain.act(delta);
Gdx.gl.glClearColor(.125f, .125f, .125f, 0);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gameCamera.update();
g.mapMgr.updateNPCS();
sprBatch.setProjectionMatrix(gameCamera.combined);
sprBatch.begin();
g.mapMgr.draw(gameCamera, new int[] {0,1});
sMain.draw(); // Draw player/NPCs
//g.getPlayer().draw(sprBatch, 0f);
g.mapMgr.drawCollisionRectangles(gameCamera);
sprBatch.end();
}
}
#Override
public void resize(int width, int height) {g.debugOut(TAG,"resize("+width+","+height+")");}
#Override
public void resume() {g.togglePause(false);g.debugOut(TAG, "resume()");}
#Override
public void show() {
g.debugOut(TAG, "show()");
g.inputController.addProcessor(sMain);
g.updateInput();
}
}
I am not sure what's going on but was pretty sure I could override draw before.
You must override it like this:
#Override
public void draw(Batch batch, float parentAlpha) {
Gdx.app.log(getName(), "Drawing player");
}
Change the SpriteBatch to Batch. Reference Actor#draw

Categories