libGDX textures are "stretched" - java

I am currently working with libGDX and got to a strange problem.
The textures that I use with batch and rectangles are stretched. Here is a picture.
As you can see, the background looks completely normal, but the person in the middle is a lot taller than the person in the left corner, which it should look like.
Here is my code:
import java.util.Iterator;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.utils.Array;
import com.data.Manager;
public class GameScreen implements Screen{
private Texture backgroundTexture = Manager.manager.get(("Ressources/Hintergrund_Skizze.png"), Texture.class);
private Texture farmerBackTexture = Manager.manager.get(("Ressources/Farmer_Back_Skizze.png"), Texture.class);
private Texture farmerRightTexture = Manager.manager.get(("Ressources/Farmer_Right_Skizze.png"), Texture.class);
private Texture farmerLeftTexture = Manager.manager.get(("Ressources/Farmer_Left_Skizze.png"), Texture.class);
private Texture ufoTexture = Manager.manager.get(("Ressources/Ufo_Skizze.png"), Texture.class);
private Texture laserTexture = Manager.manager.get(("Ressources/Magic_Ball.png"), Texture.class);
private Image backgroundImage = new Image(backgroundTexture);
private Image farmerBackImage = new Image(farmerBackTexture);
private Stage levelStage = new Stage(), menuStage = new Stage();
private Table menuTable = new Table();
private Skin menuSkin = Manager.menuSkin;
private OrthographicCamera camera;
private SpriteBatch batch;
private Rectangle farmer, ufo;
private Array<Rectangle> lasers;
private boolean ufoMovementLeft = true;
private boolean leftArrow = false;
private boolean rightArrow = false;
private float laserMovement = 0;
private int ufoLife = 15;
#Override
public void show() {
levelStage.addActor(backgroundImage);
levelStage.addActor(farmerBackImage);
Gdx.input.setInputProcessor(levelStage);
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
batch = new SpriteBatch();
farmer = new Rectangle();
farmer.x = 800 / 2 - 80 / 2; farmer.y = 80;
farmer.width = 80; farmer.height = 270;
ufo = new Rectangle();
ufo.x = 800 / 2; ufo.y = 375;
ufo.width = 185; ufo.height = 94;
lasers = new Array<Rectangle>();
}
public void movement() {
if(Gdx.input.isKeyPressed(Keys.LEFT)) leftArrow = true;
if(!Gdx.input.isKeyPressed(Keys.LEFT)) leftArrow = false;
if(Gdx.input.isKeyPressed(Keys.RIGHT)) rightArrow = true;
if(!Gdx.input.isKeyPressed(Keys.RIGHT)) rightArrow = false;
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
levelStage.act();
levelStage.draw();
batch.setProjectionMatrix(camera.combined);
batch.begin();
movement();
if(leftArrow) {if(farmer.x >= 60) farmer.x -= 2; batch.draw(farmerLeftTexture, farmer.x, farmer.y);}
else if(rightArrow) {if(farmer.x <= 590) farmer.x += 2; batch.draw(farmerRightTexture, farmer.x, farmer.y);}
else batch.draw(farmerBackTexture, farmer.x, farmer.y);
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() {
levelStage.dispose(); menuStage.dispose();
menuSkin.dispose();
ufoTexture.dispose();
laserTexture.dispose();
farmerBackTexture.dispose();
farmerRightTexture.dispose();
farmerLeftTexture.dispose();
}}
I hope you are able to help me find the mistake.
Cheers,
Joshflux
EDIT: I am pretty sure, that it has to do something with the size of the window. If I resize the height of the window from 800 to 200, the person in the left corner looks the same, but the person in the middle is way smaller. Still can't figure out how to solve it though...

The problem is that your levelStage uses a different camera.
new Stage();
Creates a stage with its own camera and a scaling viewport. And here you create another camera:
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
Note that this does NOT set the window size!
With a static size, as you never update it when you resize the window.
Since you use a stage for your level you could do this:
batch.setProjectionMatrix(levelStage.getCamera().combined);
If you don't want a scaling viewport create your own (take a look a the different viewports) and add it as an parameter to new Stage(viewport).
To set the window size you need to go to the desktop project and change it in the config class.

That happens because you are adding an actor to a scene and just drawing an texture after. you could use some information about differences of actors and texture drawing here:
libgdx difference between sprite and actor
When to use actors in libgdx? What are cons and pros?

Related

Accessing elements inside a GraphicsContext in JavaFX canvas

I'm implementing a simple hockey game following an MVC pattern. I'm having trouble refreshing the player's position, which I have created inside a canvas using the GraphicsContext.drawImage() method. I'm inside an AnimationTimer anonymous class, inside the handle method.
The positions and boundaries are all reflected to the backend,so I don't really need to do any particular logic here, I just want to refresh the player's position on every frame, based on its position calculated inside the model, but I can't access the image I've drawn before in any way. Here's the code:
DefaultController controller;
#FXML
public void initialize() {
controller = new DefaultController(800, 400);
double playerX = controller.getField().getPlayer().getX();
double playerY = controller.getField().getPlayer().getY();
double enemyX = controller.getField().getEnemy().getX();
double enemyY = controller.getField().getEnemy().getY();
context.drawImage(new Image("player.png"),playerX, playerY);
context.drawImage(new Image("enemy.png"),enemyX, enemyY);
AnimationTimer timer = new AnimationTimer() {
#Override
public void handle(long now) {
pane.getScene().addEventHandler(KeyEvent.KEY_PRESSED, (key) -> {
if (key.getCode() == KeyCode.UP) {
controller.getField().getPlayer().setLocation(playerX,playerY-0.1)
// how do I update the player image position inside the canvas?
}
});
}
};
timer.start();
}
You are following a completely wrong approach. You cannot update anything in a Canvas once it is drawn. You can just erase it and redraw it again. For what you are trying to do the scene graph is much better suited.
The following is an mre demonstrating how to move an image on a canvas using the UP key:
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.*;
import javafx.scene.image.Image;
import javafx.scene.input.*;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Main extends Application {
private static final int SIZE = 200;
private static final String FISH_IMAGE = "https://www.shareicon.net/data/128x128/2015/03/28/14104_animal_256x256.png";
private Image image;
private Canvas canvas;
private final double xPos = 250;
private double yPos = 150;
private static final double MOVE = 0.8;
#Override
public void start(Stage primaryStage) {
image = new Image(FISH_IMAGE,SIZE,SIZE,false,false);
canvas = new Canvas(SIZE*3, SIZE*3);
draw();
Scene scene = new Scene(new StackPane(canvas));
scene.addEventHandler(KeyEvent.KEY_PRESSED, (key) -> animate(key));
primaryStage.setScene(scene);
primaryStage.show();
AnimationTimer timer = new AnimationTimer() {
#Override
public void handle(long now) {
//to avoid multiple handlers do not add handler here
draw();
}
};
timer.start();
}
private void animate(KeyEvent key){
if(key.getCode()== KeyCode.UP) {
yPos -= MOVE;
}
//todo add down, left , right
//for low rate animation, like response to key-press, invoke draw() here instead of using AnimationTimer
}
private void draw(){
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());//clear previous
gc.drawImage(image, xPos, yPos);
}
public static void main(String[] args) {
launch(args);
}
}

Using the Sprite class for Animation in LibGDX

I'm making a simple game in LibGDX. I want to use the Sprite classes methods for my main player, while using the Animation class in order to animate the player as well. I've gotten Animation to work, I just haven't been able to integrate it with the Sprite class.
Here is my code:
package com.mygdx.game;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.utils.Array;
public class Game extends ApplicationAdapter {
SpriteBatch batch;
private TextureAtlas runAtlas;
private Animation runAnimation;
private TextureAtlas idleAtlas;
private Animation idleAnimation;
private TextureRegion currentIdleFrame;
private Sprite player;
private float elapsedTime = 0;
private float playerX = 10;
private float playerY = 10;
#SuppressWarnings({ "unchecked", "rawtypes" })
#Override
public void create () {
batch = new SpriteBatch();
runAtlas = new TextureAtlas(Gdx.files.internal("runSpritesheet.atlas"));
runAnimation = new Animation(1/12f, runAtlas.getRegions());
idleAtlas = new TextureAtlas(Gdx.files.internal("idleSpritesheet.atlas"));
idleAnimation = new Animation(1/3f, idleAtlas.getRegions());
player = new Sprite();
}
#Override
public void render () {
currentIdleFrame = (TextureRegion) idleAnimation.getKeyFrame(elapsedTime, true);
elapsedTime += Gdx.graphics.getDeltaTime();
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
if(Gdx.input.isKeyPressed(Keys.DPAD_RIGHT)) {
batch.draw((TextureRegion) runAnimation.getKeyFrame(elapsedTime, true), playerX, playerY);
} else if (Gdx.input.isKeyPressed(Keys.DPAD_LEFT)) {
batch.draw((TextureRegion) runAnimation.getKeyFrame(elapsedTime, true), playerX, playerY);
} else {
player.setRegion(currentIdleFrame);
player.draw(batch);
}
batch.end();
}
#Override
public void dispose () {
batch.dispose();
runAtlas.dispose();
idleAtlas.dispose();
}
}
The focus is on the idle animation of the player in the "else" statement. I try setting the player sprite region to the current key frame of the idle animation sprite sheet. However, when I launch the game, no sprite with the idle animation comes up. I don't get any errors either. I am hoping someone knows how to fix this problem. Thanks for reading.

libgdx background image not displaying

I have in the constructor:
backgroundTexture = new Texture(Gdx.files.internal("Pantalla.jpg"));
And in the render():
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0.2f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
myGame.batch.setProjectionMatrix(camera.combined);
myGame.batch.begin();
myGame.batch.draw(backgroundTexture, 0, 0);
stage.draw();
myGame.batch.end();
}
The full code of the class is:
package states;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import mx.itesm.mty.MyGame;
public class MenuState implements Screen{
final MyGame myGame;
Skin skin;
Skin skinPant;
Stage stage;
SpriteBatch batch;
TextButton.TextButtonStyle textButtonStyle1;
TextButton.TextButtonStyle textButtonStyle2;
TextButton.TextButtonStyle textButtonStyle3;
TextButton.TextButtonStyle textButtonStyle4;
TextureAtlas buttonAtlas;
BitmapFont font;
Texture backgroundTexture;
Sprite backgroundSprite;
OrthographicCamera camera;
public MenuState(final MyGame game) {
myGame = game;
camera = new OrthographicCamera();
camera.setToOrtho(false,800,480);
batch = new SpriteBatch();
skin = new Skin();
font = new BitmapFont();
stage = new Stage();
Gdx.input.setInputProcessor(stage);
buttonAtlas = new TextureAtlas(Gdx.files.internal("boton.atlas"));
skin.addRegions(buttonAtlas);
backgroundTexture = new Texture(Gdx.files.internal("Pantalla.jpg"));
backgroundSprite = new Sprite(backgroundTexture);
textButtonStyle1 = new TextButton.TextButtonStyle();
textButtonStyle1.font = font;
textButtonStyle1.down = skin.getDrawable("Inicio");
textButtonStyle1.up = skin.getDrawable("Inicio");
textButtonStyle1.checked = skin.getDrawable("Inicio");
TextButton buttonPlay = new TextButton("", textButtonStyle1);
textButtonStyle2 = new TextButton.TextButtonStyle();
textButtonStyle2.font = font;
textButtonStyle2.down = skin.getDrawable("Instrucciones");
textButtonStyle2.up = skin.getDrawable("Instrucciones");
textButtonStyle2.checked = skin.getDrawable("Instrucciones");
TextButton buttonInst = new TextButton("",textButtonStyle2);
textButtonStyle3 = new TextButton.TextButtonStyle();
textButtonStyle3.font = font;
textButtonStyle3.down = skin.getDrawable("Informacion");
textButtonStyle3.up = skin.getDrawable("Informacion");
textButtonStyle3.checked = skin.getDrawable("Informacion");
TextButton buttonInfo = new TextButton("",textButtonStyle3);
textButtonStyle4 = new TextButton.TextButtonStyle();
textButtonStyle4.font = font;
textButtonStyle4.down = skin.getDrawable("Salir");
textButtonStyle4.up = skin.getDrawable("Salir");
textButtonStyle4.checked = skin.getDrawable("Salir");
TextButton buttonSalir = new TextButton("",textButtonStyle4);
buttonPlay.setWidth(300f);
buttonPlay.setHeight(100f);
buttonPlay.setPosition(Gdx.graphics.getWidth() / 2 - 150f, Gdx.graphics.getHeight() / 2);
buttonInst.setWidth(300f);
buttonInst.setHeight(100f);
buttonInst.setPosition(Gdx.graphics.getWidth() / 2 - 150f, Gdx.graphics.getHeight() / 2 - 120f);
buttonInfo.setWidth(300f);
buttonInfo.setHeight(100f);
buttonInfo.setPosition(Gdx.graphics.getWidth() / 2 - 150f, Gdx.graphics.getHeight() / 2 - 240f);
buttonSalir.setWidth(300f);
buttonSalir.setHeight(100f);
buttonSalir.setPosition(Gdx.graphics.getWidth() / 2 - 150f, Gdx.graphics.getHeight() / 2 - 360f);
buttonPlay.addListener(new ChangeListener() {
#Override
public void changed(ChangeEvent event, Actor actor) {
myGame.setScreen(new PlayMenuState(myGame));
}
});
buttonInst.addListener(new ChangeListener() {
#Override
public void changed(ChangeEvent event, Actor actor) {
myGame.setScreen(new PlayMenuState(myGame));
}
});
buttonInfo.addListener(new ChangeListener() {
#Override
public void changed(ChangeEvent event, Actor actor) {
myGame.setScreen(new PlayMenuState(myGame));
}
});
buttonSalir.addListener(new ChangeListener() {
#Override
public void changed(ChangeEvent event, Actor actor) {
myGame.setScreen(new PlayMenuState(myGame));
}
});
stage.addActor(buttonPlay);
stage.addActor(buttonInst);
stage.addActor(buttonInfo);
stage.addActor(buttonSalir);
}
#Override
public void show() {
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0.2f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
myGame.batch.setProjectionMatrix(camera.combined);
myGame.batch.begin();
myGame.batch.draw(backgroundTexture, 0, 0);
stage.draw();
myGame.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() {
}
}
I add several buttons and the background image. The image is in the assets folder but it juts doesn't show up.
And I had a doubt about rectangles that if there is a way to add an image to a Rectangle object the same way you set the x, y, height, width?
A Stage has it's own batch which will call begin() and end(), unless you specifically set the stage to use the same batch, the begin() and end() calls will conflict.
However you also might want to clean up your code, because you create a background sprite but not use it. I would recommend using this in stead of directly drawing the texture though (because a sprite can also have a position and other attributes which you can manipulate).

How to play music using libgdx

I have had trouble playing music using libgdx. My code is as follows:
package com.me.fixGame;
import java.util.Random;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
//import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.utils.Scaling;
import com.sun.jmx.snmp.tasks.Task;
public class fixGame implements ApplicationListener {
SpriteBatch batch;
SpriteBatch spriteBatch;
Texture trash;
Texture paper;
SpriteBatch spritebatch;
Vector2 position;
Vector2 pas;
boolean collide;
boolean countMe=false;
Vector2 size;
Vector2 size2;
Vector2 pos;
Rectangle bounds;
float posSpeed=30;
Rectangle bounds2;
float delay = 1; // seconds
boolean counted= false;
int score = 3;
//Texture Gogreen;
String myScore;
Texture background;
CharSequence str = "Lives left: 3"; // = myScore;
CharSequence line = "Score: 0"; // = myScore;
String myLife;
int life=0;
BitmapFont font;
float x;
float y;
Sound sound;
boolean collision = false;
#Override
public void create() {
//Gogreen = new Texture(Gdx.files.internal("data/gogreenNow.jpg"));
background = new Texture(Gdx.files.internal("data/trash.png"));
x= background.getWidth();
y=background.getHeight();
//float delaySeconds = 1;
spriteBatch = new SpriteBatch();
trash = new Texture(Gdx.files.internal("data/trash.png"));
paper = new Texture(Gdx.files.internal("data/paper1.jpg"));
sound = Gdx.audio.newSound(Gdx.files.internal("data/testjava.mp3"));
position = new Vector2(100, 50);
pos = new Vector2(54, 14);
batch = new SpriteBatch();
BitmapFont font = new BitmapFont();
size2 = new Vector2(trash.getWidth() ,trash.getHeight() );
//size2.y = trash.getHeight();
//size2.x = trash.getWidth();
size = new Vector2(paper.getWidth() ,paper.getHeight());
bounds= new Rectangle(pos.x, pos.y, size.x, size.y);
bounds2= new Rectangle(position.x, position.y, size2.x, size2.y);
}
#Override
public void dispose() {
}
public void update(){
bounds.set(pos.x, pos.y, size.x, size.y);
bounds2.set(position.x, position.y, size2.x, size2.y);
float pos1=Gdx.input.getAccelerometerX();
//if(pos1<0)
// pos1=(-1)*pos1;
position.x = position.x - 5*pos1;
}
#Override
public void render() {
sound.play(0.5f);
sound.dispose();
if(bounds.overlaps(bounds2)){
collision=true;
counted=true;
}else{
collision=false;
}
if(collision==true){
}
if(pos.y<640){
counted=false;
} else if(pos.y > 640 && collision==false && counted==false){
counted=true;
score= score-1;
myScore = "Lives left: " + score;
str = myScore;
}
if(bounds.overlaps(bounds2)){
countMe=true;
life= life+50;
myLife = "Score: " + life;
line = myLife;
}
if(position.x<0){
position.x= position.x+11;
}
if(position.x>425){
position.x= position.x-11;
}
update();
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
pos.y=pos.y-posSpeed;
//posSpeed = posSpeed+(2/3);
if(pos.y<0){
pos.y = 700;
Random randomGenerator = new Random();
pos.x = randomGenerator.nextInt(500);
}
BitmapFont font = new BitmapFont();
batch.begin();
batch.draw(background, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
if (!collision) {
batch.draw(paper, pos.x, pos.y);
}
//batch.draw(paper, pos.x, pos.y);
batch.draw(trash, position.x, position.y);
font.setScale(3);
font.setColor(0.0f, 0.0f, 1.0f,1.0f);
font.draw(batch, str, 300,900);
font.draw(batch, line, 300, 950);
batch.end();
font.dispose();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
My sound file I call over here:
sound = Gdx.audio.newSound(Gdx.files.internal("data/testjava.mp3"));
And the code I use to play it is:
sound.play();
sound.dispose();
For some reason it does not work on my desktop and my phone. I tested the the sound file actually had some sound in it.
You need to get rid of the sound.dispose(); call right after playing the sound, since it will dispose the sound file ;)
Just put it into your game's dispose(); method, so it will get removed after the game is done.
Also, you shouldn't call sound.play(0.5f); within your render-loop. Remember this function will get called about 60 times a second and you don't want to have the sound start 60 times a second.
So if it's some kind of sound effect that comes with a special event, like firing a bullet or hitting a target etc, just call sound.play(); one time, when you are actually firing the event.
https://github.com/libgdx/libgdx/wiki/Sound-effects
If you want to play background music, you should try streaming the music file. The wiki is awesome for that: https://github.com/libgdx/libgdx/wiki/Streaming-music
Hope it helps :)

How to restart my game once the user has quit(Libgdx)

In my libgdx game it functions how i want it to but when i exit the game it starts of from where i was before, i want it to restart. The code is as follows.
package com.me.fixGame;
import java.util.Random;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
//import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.utils.Scaling;
import com.sun.jmx.snmp.tasks.Task;
public class fixGame implements ApplicationListener {
SpriteBatch batch;
SpriteBatch spriteBatch;
Texture trash;
Texture paper;
SpriteBatch spritebatch;
Vector2 position;
Vector2 pas;
boolean collide;
boolean countMe=false;
Vector2 size;
Vector2 size2;
Vector2 pos;
Rectangle bounds;
float posSpeed=30;
Rectangle bounds2;
float delay = 1; // seconds
boolean counted= false;
int score = 3;
//Texture Gogreen;
String myScore;
Texture background;
CharSequence str = "Lives left: 3"; // = myScore;
CharSequence line = "Score: 0"; // = myScore;
String myLife;
int life=0;
BitmapFont font;
float x;
float y;
boolean collision = false;
#Override
public void create() {
//Gogreen = new Texture(Gdx.files.internal("data/gogreenNow.jpg"));
background = new Texture(Gdx.files.internal("data/trash.png"));
x= background.getWidth();
y=background.getHeight();
//float delaySeconds = 1;
spriteBatch = new SpriteBatch();
trash = new Texture(Gdx.files.internal("data/trash.png"));
paper = new Texture(Gdx.files.internal("data/paper1.jpg"));
position = new Vector2(100, 50);
pos = new Vector2(54, 14);
batch = new SpriteBatch();
BitmapFont font = new BitmapFont();
size2 = new Vector2(trash.getWidth() ,trash.getHeight() );
//size2.y = trash.getHeight();
//size2.x = trash.getWidth();
size = new Vector2(paper.getWidth() ,paper.getHeight());
bounds= new Rectangle(pos.x, pos.y, size.x, size.y);
bounds2= new Rectangle(position.x, position.y, size2.x, size2.y);
}
#Override
public void dispose() {
}
public void update(){
bounds.set(pos.x, pos.y, size.x, size.y);
bounds2.set(position.x, position.y, size2.x, size2.y);
float pos1=Gdx.input.getAccelerometerX();
//if(pos1<0)
// pos1=(-1)*pos1;
position.x = position.x - 5*pos1;
}
#Override
public void render() {
if(bounds.overlaps(bounds2)){
collision=true;
counted=true;
}else{
collision=false;
}
if(collision==true){
}
if(pos.y<640){
counted=false;
} else if(pos.y > 640 && collision==false && counted==false){
counted=true;
score= score-1;
myScore = "Lives left: " + score;
str = myScore;
}
if(bounds.overlaps(bounds2)){
countMe=true;
life= life+50;
myLife = "Score: " + life;
line = myLife;
}
if(position.x<0){
position.x= position.x+11;
}
if(position.x>425){
position.x= position.x-11;
}
update();
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
pos.y=pos.y-posSpeed;
//posSpeed = posSpeed+(2/3);
if(pos.y<0){
pos.y = 700;
Random randomGenerator = new Random();
pos.x = randomGenerator.nextInt(500);
}
BitmapFont font = new BitmapFont();
batch.begin();
batch.draw(background, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
if (!collision) {
batch.draw(paper, pos.x, pos.y);
}
//batch.draw(paper, pos.x, pos.y);
batch.draw(trash, position.x, position.y);
font.setScale(3);
font.setColor(0.0f, 0.0f, 1.0f,1.0f);
font.draw(batch, str, 300,900);
font.draw(batch, line, 300, 950);
batch.end();
font.dispose();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
I searched through out the web and I could not find anything. Does anybody have any answers?
Any help would be appreciated thanks in advance.
Are you talking about desktop or Android?
Assuming you're talking about Android, when the user exits the game, the pause() function is called. When the user goes back to the game, the resume() function is called.
I would bet that your game would "reset" if you ran some other apps between exiting and resuming the game. Normally people save the state of the game in pause() and then load it in resume(), but for your case, it sounds like you just want to reset it each time.
If all of the above is actually true for you, just reset the game state in the resume() function.
For Android: If the user presses the "Home" button or a call is incoming the games pause() method is called. If the user returns after the call or after some time normally resume() is called. But if the Android OS decided to close your app, create() will be called, and if you do not store savegames i am sure it would reset the game.
In your case the user did not exit the game but "pause" it by pressing "Home" button. To reset the game then, you could call dispose() in your pause() method, and in dispose you simply close your app. On Desktop pause() is called if you switch window or minimize the app, as far as i know. If you do not want to close the app in this case you have to controll, if it is desktop or android.

Categories