How to play music using libgdx - java

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 :)

Related

LibGdx Chess Board

I try to create a chess board, just the board in libGdx but for some reason, I can't.
I still miss two other rows in the chess. I will show you my code, maybe you can find the problem in my code, if not, I can easily accept another solution.
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.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.MapLayers;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.maps.tiled.tiles.StaticTiledMapTile;
import com.badlogic.gdx.utils.ScreenUtils;
import com.badlogic.gdx.utils.viewport.Viewport;
public class MyGdxGame extends ApplicationAdapter {
SpriteBatch batch;
Texture img;
private OrthographicCamera camera;
private OrthogonalTiledMapRenderer render;
private final static int width = 100, height = 80, layercount = 8;
private TiledMap map;
#Override
public void create() {
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera(w, h);
Pixmap pixmap = new Pixmap(100, 80, Format.RGBA8888);
pixmap.setColor(Color.WHITE); // add your 1 color here
pixmap.fillRectangle(0, 0, 80, 80);
pixmap.setColor(Color.BLACK); // add your 2 color here
pixmap.fillRectangle(0, 0, 80, 80);
// the outcome is an texture with an blue left square and an red right
// square
Texture t = new Texture(pixmap);
TextureRegion reg1 = new TextureRegion(t, 0, 0, 80, 80);
TextureRegion reg2 = new TextureRegion(t, 80, 0, 80, 80);
TiledMap map = new TiledMap();
MapLayers layers = map.getLayers();
for (int l = 0; l < layercount; l++) {
TiledMapTileLayer layer = new TiledMapTileLayer(width, height, 80,
80);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
Cell cell = new Cell();
if (y % 2!= 0) {
if (x % 2 != 0) {
cell.setTile(new StaticTiledMapTile(reg1));
} else {
cell.setTile(new StaticTiledMapTile(reg2));
}
} else {
if (x % 2 != 0) {
cell.setTile(new StaticTiledMapTile(reg2));
} else {
cell.setTile(new StaticTiledMapTile(reg1));
}
}
layer.setCell(x, y, cell);
}
}
layers.add(layer);
}
render = new OrthogonalTiledMapRenderer(map);
render.setView(camera);
camera.translate(Gdx.graphics.getWidth() / 2,
Gdx.graphics.getHeight() / 2);
}
#Override
public void dispose() {
render.dispose();
map.dispose();
}
private static final float movmentspeed = 5f;
#Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
render.setView(camera);
render.render();
if (Gdx.input.isKeyPressed(Keys.LEFT)) {
camera.translate(-movmentspeed, 0);
} else if (Gdx.input.isKeyPressed(Keys.RIGHT)) {
camera.translate(movmentspeed, 0);
} else if (Gdx.input.isKeyPressed(Keys.UP)) {
camera.translate(0, movmentspeed);
} else if (Gdx.input.isKeyPressed(Keys.DOWN)) {
camera.translate(0, -movmentspeed);
}
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
Here is my code. I need a solution to this as fast as possible if you can...
Your second call to
pixmap.setColor(Color.BLACK); // add your 2 color here
pixmap.fillRectangle(0, 0, 80, 80);
overwrites the colour set by the first because you are writing to the same area.
Within the nested loop iterating over the board, you could simplify finding the alternating cell type for the chessboard to
if ((x+(y*8)) % 2 = 0 ) {
//Cell is bottom left square color
} else {
//Cell is the other colour
}
Although its nice to generate the chess board for special effects later, you could also just import one from the tiled editor and then you can experiment more with how it looks. Tile map loaders absolutely not the pain you might imagine they are super short, literally a snippets worth, there is a written loader here
https://gamefromscratch.com/libgdx-tutorial-11-tiled-maps-part-1-simple-orthogonal-maps/
(also and not relevant this
Pixmap pixmap = new Pixmap(100, 80, Format.RGBA8888); is a larger region than you ever use.)
There is a no AI libGDX chess game here as well if you want to just extend with AI.
https://github.com/axlan/libgdx-chess

libGDX textures are "stretched"

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?

LibGDX HealthBar: How can i improve it

I have been making a simple game using LibGDX and now I am trying to add a health bar in my game.
I have successfully added the health bar in the game and it is working fine at this moment.
The problem , however, is how to further modify this code like professionals do.
I am still in learning process so I have been trying to figure how to further make it look
better, succinct, and professional but wan't able to furnish it further.
I have pasted my HealthBar class code below. I will appreciate any suggestion so that I can think better and efficient when writing any codes in future.
public class HealthBar extends Actor{
protected float MaxHealthX;
protected static float HealthBarY= 36;
float decreaseRate = 0;
float addHealth = 0;
float deductHealth = 0;
ShapeRenderer sr;
static private boolean projectionMatrixSet;
private boolean isHitE = false;
private boolean isHitI = false;
float totalSubractedHP = 0;
float totalAddedHP = 0;
public HealthBar(){
sr = new ShapeRenderer();
projectionMatrixSet = false;
}
#Override
public void draw(Batch batch, float parentAlpha){
//if a main character is hit by enemy
if(isHitE==true){
//subtractHP();
totalSubractedHP += 1;
isHitE = false;
}
if(isHitI==true){
totalAddedHP += 10;
isHitI = false;
}
MaxHealthX=296-decreaseRate+totalAddedHP-totalSubractedHP;
batch.end();
if(!projectionMatrixSet){
sr.setProjectionMatrix(batch.getProjectionMatrix());
}
sr.begin(ShapeType.Filled);
sr.setColor(Color.BLACK);
sr.rect(40,650,300,40);
if(isOutOfHealth() == false){
sr.setColor(Color.RED);
sr.rect(42, 652, MaxHealthX, HealthBarY);
}
sr.end();
batch.begin();
}
//updating health decrease rate as time passes by
public void updateHealthBar(float delta) {
decreaseRate += 10*delta;
}
//checks whether health is greater than zero
public boolean isOutOfHealth(){
if(MaxHealthX > 0){
return false;
}else{
return true;
}
}
//checking if hit by enemy
public boolean isHitByEnemy(){
isHitE = true;
return isHitE;
}
public boolean isHitByItem(){
isHitI = true;
return isHitI;
}
ShapeRenderer is normaly only used for debuging. In the endgame most times only SpriteBatch is used.
In the draw method you call batch.end() which calls flush(). This method is a bit "heavy" and should only be called, if it is really neccessary. So in your case it would be better to use batch instead of ShapeRenderer to draw the whole HealthBar.
Even better:
Use the Scene2D Progressbar, which should be exactly what you are looking for.
This ProgressBar need a range (for example min = 0, max = 100), a stepSize (for example 1.0) a boolean vertical, and a ProgressBarStyle.
The ProgressBarStyle in your case just needs 2 Drawables:
backgroung
disabledBackground
You can then use setValue(maxHealthX), which will set the background from 0-maxHealthX (rounded to the nearest stepSize) and disabledBackground from maxHealthX-end of progressbar.
This is how you can do it ,implement logic your self
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class MyGdxGame extends ApplicationAdapter {
SpriteBatch batch;
int i=0;
Texture texture,texture2;
#Override
public void create () {
batch = new SpriteBatch();
initTestObjects() ;
}
#Override
public void render () {
Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(texture2,100,100,300,20);
batch.draw(texture,100,100,i,20);
if(i>300)
{
i=0;
}
i++;
batch.end();
}
private void initTestObjects() {
int width =1 ;
int height = 1;
Pixmap pixmap = createProceduralPixmap(width, height,0,1,0);
Pixmap pixmap2 = createProceduralPixmap(width, height,1,0,0);
texture = new Texture(pixmap);
texture2 = new Texture(pixmap2);
}
private Pixmap createProceduralPixmap (int width, int height,int r,int g,int b) {
Pixmap pixmap = new Pixmap(width, height, Format.RGBA8888);
pixmap.setColor(r, g, b, 1);
pixmap.fill();
return pixmap;
}
}

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.

Java, Slick, An object that shouldnt move is moving?

In my game I'm making, I need NPC's/mobs.
I made a class called peasant (my first mob).
In the main class from which the game is running, I have all the information, as well as calling an object called mob1 from Peasant
I need to make it so that if the player is within 300 pixels of the mob, it starts to move towards it. Ive tried doing this but so far, even if the player is 2000 pixels away, the mob starts moving???
Here is my Peasant class
package Entitys.NPCs;
public class Peasant {
public Peasant(float InitX, float InitY, int MobID){
MobX = InitX;
MobY = InitY;
}
//This class shall be used as an object creator. This will randomly move a graphic around, near to a player
private float MobX;
private float MobY;
private int AmountMoved = 0;
private boolean MoveRight = true;
private boolean MoveLeft;
public boolean PlayerDetected = false;
long timer;
//Used to find the mobs X
public float getX(){
return MobX;
}
//Used to find the mobs Y
public float getY(){
return MobY;
}
//Used to set the mobs X
public void setX(float X){
MobX = X;
}
//Used to set the mobs Y
public void setY(float Y){
MobY = Y;
}
//Used to simply move the mob on its X co-ords
public void moveX(int delta){
MobX += delta*0.1f;
}
//Used to simply move the mob on its Y co-ords
public void moveY(int delta){
MobY += delta*0.1f;
}
public void autoEveryThing(int delta, float playerX, float playerY) {
// If the player has not been spotted the NPC/Mob will move left and
// right by 100 Pixels.
if(MobX-300<playerX){
PlayerDetected=true;
}
if(PlayerDetected=true){
if(MobX>playerX){
MobX-=delta*0.12;
}
}
}
}
And here is the main class:
package Worlds.World1;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.Animation;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
import Entitys.NPCs.*;
import Main.SimpleMob;
public class World1A extends BasicGameState{
String mousePosition;
Image world;
Animation player, playerLeft, playerRight;
int[] duration = {200,200};
float playerX;
float playerY;
float WorldX;
float WorldY;
float PlayerVisibleScreenX;
float PlayerVisibleScreenY;
String MovementDirection;
Peasant mob1;
public World1A(int state){
}
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException{
Image [] WalkingLeft = {new Image("res/Sprites/buckysLeft.png"),new Image("res/Sprites/buckysLeft.png")};
Image [] WalkingRight = {new Image("res/Sprites/buckysRight.png"),new Image("res/Sprites/buckysRight.png")};
playerLeft = new Animation(WalkingLeft, duration, false);
playerRight = new Animation(WalkingRight, duration, false);
player = playerRight;
WorldX = 0;
WorldY = 0;
world= new Image("res/WorldImages/WorldBackGround.png");
mousePosition="null";
MovementDirection = "Not Moved Yet";
mob1= new Peasant(2000, 200, 1);
if(WorldX<=0){
playerX = Math.abs(WorldX);
}else{
playerX=0-WorldX;
}
}
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException{
player.draw(450, 300);
if(WorldX>0){
world.draw(0, 0);
g.fillOval(0+mob1.getX(), 0+mob1.getY(), 50, 50);
g.fillRect(0, 0+340, 500, 10);
player.draw(-WorldX + 450, 300);
}else{
world.draw(WorldX, WorldY);
g.fillOval(WorldX+mob1.getX(), WorldY+mob1.getY(), 50, 50);
g.fillRect(WorldX, WorldY+340, 500, 10);
g.fillOval(WorldX+mob1.getX(), WorldY+mob1.getY(), 50, 50);
player.draw(450, 300);
}
g.setColor(Color.white);
//All this is co-ords ect, it is for developement help
g.drawString(String.valueOf(mob1.getX()), 50, 200);
g.drawString("World X: "+ String.valueOf(WorldX), 50, 225);
g.drawString("Player X: "+ String.valueOf(playerX), 50, 250);
g.drawString("Player Detetcted?: "+ String.valueOf(mob1.PlayerDetected), 50, 265);
}
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException{
if(WorldX<=0){
playerX = Math.abs(WorldX);
}else{
playerX=0-WorldX;
}
mob1.autoEveryThing(delta, playerX, playerY);
int posX = Mouse.getX();
int posY = Mouse.getY();
mousePosition = "X: " + posX + "\nY: " + posY;
Input input = gc.getInput();
if(input.isKeyDown(Input.KEY_LEFT)){
WorldX += delta * 0.1f;
MovementDirection = "Left";
player = playerLeft;
}else if(input.isKeyDown(Input.KEY_RIGHT)){
WorldX -= delta * 0.1f;
MovementDirection = "Right";
player = playerRight;
}else{
MovementDirection = "Not Moving";
}
}
//DO NOT CHANGE
public int getID(){
return 2;
}
}
The autoEveryThing method in the Peasant class should make it so that if(mobX-300
But when I first run this it starts moving towards the player?
even though (2000-300<0) is false, it still sets the PlayerDetected boolean to true???
Why does this happen?
Thanks
EDIT:
After trying to go through thi and fix it I found somthing strange, even if I take out the whole bit which can change PlayerDetected to true, the mob still moves towards the player. This meens that PlayerDetected is becominbg true somwhere, but I cant figure out where?
if(PlayerDetected=true){
is wrong you should use ==
if(PlayerDetected==true){
or even better
boolean isPlayerDetected;
if (isPlayerDetected)
further consider
double dx = mobX - playerX;
double dy = mobY - playerY;
double distance = Math.sqrt(dx*dx + dy*dy);
if (distance < 300) {
// is within distacne threshold
}

Categories