Why doesn't libgdx button work every time? - java

I made a button, witch stops the game. The is a menu, where you can continue the game. But if the cam moves with the player, the button doesn't work any more. You can see it, but if you click on it nothing happens. If you come back to the "start position" of the cam, the button works again. But the InputProcessor is always the stage with the button.
public class PlayState extends State {
//Objects
private final GameStateManager gameStateManager;
private final State me;
private EntityManager entityManager;
private Player player;
private Texture background;
private Texture filter;
private BitmapFont font;
private Sound click, boost;
private Drug drug;
private Border border;
private House house;
//Constants
public static final int FIELD_SIZE_HEIGHT = 1000;
public static final int FIELD_SIZE_WIDTH = 500;
//Variables
private int collectedDrugs;
private boolean pause, renderLost;
private boolean boostSound;
//Button pause
private Stage stage;
private ImageButton button;
private Drawable drawable;
private Texture textureBtn;
public PlayState(GameStateManager gsm) {
super(gsm);
gameStateManager = gsm;
me = this;
entityManager = new EntityManager();
player = new Player(this, 100, 100);
border = new Border();
background = new Texture("bggame.png");
filter = new Texture("filter.png");
cam.setToOrtho(false, MinniMafia.WIDTH, MinniMafia.HEIGHT);
click = Gdx.audio.newSound(Gdx.files.internal("Click.mp3"));
boost = Gdx.audio.newSound(Gdx.files.internal("boost.mp3"));
drug = new Drug();
house = new House();
collectedDrugs = 0;
font = new BitmapFont();
entityManager.addEntity(player);
entityManager.addEntity(drug);
entityManager.addEntity(border);
entityManager.addEntity(house);
pause = false;
renderLost = false;
boostSound = false;
stage = new Stage();
textureBtn = new Texture("pausebtn.png");
drawable = new TextureRegionDrawable(new TextureRegion(textureBtn));
button = new ImageButton(drawable);
button.setPosition(cam.position.x + cam.viewportWidth/2 - 50, cam.position.y + cam.viewportHeight/2 - 50);
button.addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
gameStateManager.set(new PauseState(gameStateManager, me));
}
});
stage.addActor(button);
Gdx.input.setInputProcessor(button.getStage());
}
#Override
protected void handleInput() {
if (Gdx.input.justTouched()) {
click.play(0.2f);
}
if (Gdx.input.isTouched()) {
player.setStop(true);
boostSound = false;
} else {
if (!boostSound) {
boost.play(0.2f);
boostSound = true;
}
player.setStop(false);
}
}
#Override
public void update(float dt) {
Gdx.input.setInputProcessor(stage);
if(Gdx.input.getInputProcessor() == stage){
System.out.println("All working");
}else{
System.out.println("Error");
}
if (!pause) {
handleInput();
entityManager.updateEntities(dt);
setCam();
button.setPosition(cam.position.x + cam.viewportWidth/2 - 60, cam.position.y + cam.viewportHeight/2 - 60);
if (drug.collides(player.getBounds())) {
entityManager.disposeEntity(drug);
player.setGotDrug(true);
}
if (border.collides(player.getBounds()) && !border.isOpen()) {
pause = true;
renderLost = true;
}
if (house.collides(player.getBounds()) && player.isGotDrug()) {
player.setGotDrug(false);
collectedDrugs++;
drug = new Drug();
entityManager.addEntity(drug);
}
} else if (renderLost = true) {
if (Gdx.input.isTouched()) {
gsm.set(new MenuState(gsm));
dispose();
}
}
}
#Override
public void render(SpriteBatch sb) {
sb.setProjectionMatrix(cam.combined);
sb.begin();
sb.draw(background, 0, 0);
entityManager.renderEntities(sb);
button.draw(sb, 10f);
font.draw(sb, "" + collectedDrugs, cam.position.x - cam.viewportWidth / 2 + 10, cam.position.y - cam.viewportHeight / 2 + 20);
if (renderLost) {
sb.draw(filter, cam.position.x - cam.viewportWidth / 2, cam.position.y - cam.viewportHeight / 2);
font.draw(sb, "LOST! SCORE:" + collectedDrugs, cam.position.x - 50, cam.position.y);
}
sb.end();
}
#Override
public void dispose() {
background.dispose();
entityManager.disposeAll();
click.dispose();
}
private void setCam() {
float camViewportHalfX = cam.viewportWidth * .5f;
float camViewportHalfY = cam.viewportHeight * .5f;
cam.position.x = player.getPosition().x;
cam.position.y = player.getPosition().y;
cam.position.x = MathUtils.clamp(cam.position.x, camViewportHalfX, FIELD_SIZE_WIDTH - camViewportHalfX);
cam.position.y = MathUtils.clamp(cam.position.y, camViewportHalfY, FIELD_SIZE_HEIGHT - camViewportHalfY);
cam.update();
}
public Drug getDrug() {
return drug;
}
public House getHouse() {
return house;
}
}
I really don't know where the problem is. Could you help me please?

Related

libgdx Clicklistener doesnt work, What is missing?

Im new with libgdx. Im going to code a android game. The Player is moving by itself, but if you touch the screen(or click with the mouse) the player will stop. I want to add a pause button. It do render, but if I touch/click on the button the listener doesnt react, just the player stops.
Thats the class with the imporant methods about the button:
public class PlayState extends State {
private EntityManager entityManager;
private Player player;
private Texture background;
private Texture filter;
private BitmapFont font;
private Sound click, boost;
private Drug drug;
private Border border;
private House house;
public static final int FIELD_SIZE_HEIGHT = 1000;
public static final int FIELD_SIZE_WIDTH = 500;
private int collectedDrugs;
private boolean pause, renderLost;
private boolean boostSound;
private ImageButton button;
private Drawable drawable;
private Texture textureBtn;
public PlayState(GameStateManager gsm) {
super(gsm);
entityManager = new EntityManager();
player = new Player(this, 100, 100);
border = new Border();
background = new Texture("bggame.png");
filter = new Texture("filter.png");
cam.setToOrtho(false, MinniMafia.WIDTH, MinniMafia.HEIGHT);
click = Gdx.audio.newSound(Gdx.files.internal("Click.mp3"));
boost = Gdx.audio.newSound(Gdx.files.internal("boost.mp3"));
drug = new Drug();
house = new House();
collectedDrugs = 0;
font = new BitmapFont();
entityManager.addEntity(player);
entityManager.addEntity(drug);
entityManager.addEntity(border);
entityManager.addEntity(house);
pause = false;
renderLost = false;
boostSound = false;
Stage stage;
textureBtn = new Texture("pausebtn.png");
drawable = new TextureRegionDrawable(new TextureRegion(textureBtn));
button = new ImageButton(drawable);
button.setPosition(cam.position.x + cam.viewportWidth/2 - 50, cam.position.y + cam.viewportHeight/2 - 50);
button.addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
System.out.println("Button Pressed");
}
});
}
#Override
protected void handleInput() {
if (Gdx.input.justTouched()) {
click.play(0.2f);
}
if (Gdx.input.isTouched()) {
player.setStop(true);
boostSound = false;
} else {
if (!boostSound) {
boost.play(0.2f);
boostSound = true;
}
player.setStop(false);
}
}
#Override
public void update(float dt) {
if (!pause) {
handleInput();
entityManager.updateEntities(dt);
setCam();
button.setPosition(cam.position.x + cam.viewportWidth/2 - 60, cam.position.y + cam.viewportHeight/2 - 60);
if (drug.collides(player.getBounds())) {
entityManager.disposeEntity(drug);
player.setGotDrug(true);
}
if (border.collides(player.getBounds()) && !border.isOpen()) {
pause = true;
renderLost = true;
}
if (house.collides(player.getBounds()) && player.isGotDrug()) {
player.setGotDrug(false);
collectedDrugs++;
drug = new Drug();
entityManager.addEntity(drug);
}
} else if (renderLost = true) {
if (Gdx.input.isTouched()) {
gsm.set(new MenuState(gsm));
dispose();
}
}
}
#Override
public void render(SpriteBatch sb) {
sb.setProjectionMatrix(cam.combined);
sb.begin();
sb.draw(background, 0, 0);
entityManager.renderEntities(sb);
button.draw(sb, 10f);
font.draw(sb, "" + collectedDrugs, cam.position.x - cam.viewportWidth / 2 + 10, cam.position.y - cam.viewportHeight / 2 + 20);
if (renderLost) {
sb.draw(filter, cam.position.x - cam.viewportWidth / 2, cam.position.y - cam.viewportHeight / 2);
font.draw(sb, "LOST! SCORE:" + collectedDrugs, cam.position.x - 50, cam.position.y);
}
sb.end();
}
I suppose that there is missing sth, but I can not figure it out. Can sb help me please?
LG bttl
You have to set your Stage as InputProcessor for Scene2d to work. Documentation
For using Stage and your own code as InputProcessor, add both to an InputMultiplexer and use this.

Can't implement toggle button function outside of one screen

Hi I've implemented a toggle button for sound on my SettingsMenu, it works within this screen however when I go back to my main menu the functionality is lost and it resets back to its initial state. Any ideas how I can make it so that once it is clicked, it keeps this selection throughout every screen. I will show you the toggle button class and the settings class in which it is implemented. Thanks.
package uk.ac.qub.eeecs.game.cardDemo;
public class ToggleButtonSound extends GameObject {
protected enum ButtonState {
ON, OFF
}
private ButtonState mButtonState = ButtonState.OFF;
private SoundManager sm;
protected Bitmap mOffBitmap;
protected Bitmap mOnBitmap;
protected Bitmap mOnHoverBitmap;
protected Bitmap mOffHoverBitmap;
private Game mGame;
public boolean mMusicMuted = false;
public boolean mSoundMuted = false;
private MusicManager mMusicManager;
public ToggleButtonSound(float x, float y, float width, float height,
String offBitmap,
String onBitmap,
// String OffHoverBitmap,
//String OnHoverBitmap,
GameScreen gameScreen,
Game game) {
super(x, y, width, height,
gameScreen.getGame().getAssetManager().getBitmap(offBitmap), gameScreen);
mGame = game;
AssetStore assetStore = gameScreen.getGame().getAssetManager();
mOffBitmap = assetStore.getBitmap(offBitmap);
// mOffHoverBitmap = assetStore.getBitmap(offBitmap);
mOnBitmap = assetStore.getBitmap(onBitmap);
//mOnHoverBitmap = assetStore.getBitmap(onBitmap);
sm = new SoundManager(mGame);
mMusicManager = new MusicManager(mGame);
}
private boolean mPushTriggered;
private boolean mIsPushed;
/**
* Update the button
*
* #param elapsedTime Elapsed time information
*/
public void update(ElapsedTime elapsedTime) {
// Consider any touch events occurring in this update
Input input = mGame.getInput();
BoundingBox bound = getBound();
// Check for a press release on this button
for (TouchEvent touchEvent : input.getTouchEvents()) {
if (touchEvent.type == TouchEvent.TOUCH_UP
&& bound.contains(touchEvent.x, touchEvent.y)) {
// A touch up has occured in this control
if (mButtonState == ButtonState.OFF) {
setToggled(true);
} else {
setToggled(false);
}
return;
}
}
for (int idx = 0; idx < TouchHandler.MAX_TOUCHPOINTS; idx++) {
if (input.existsTouch(idx)) {
if (bound.contains(input.getTouchX(idx), input.getTouchY(idx))) {
if (!mIsPushed) {
mPushTriggered = true;
if (mOnHoverBitmap != null && mOffHoverBitmap != null)
mBitmap = mButtonState == ButtonState.ON ? mOnHoverBitmap : mOffHoverBitmap;
mIsPushed = true;
}
return;
}
}
}
if (mIsPushed) {
mBitmap = mButtonState == ButtonState.ON ? mOnBitmap : mOffBitmap;
mIsPushed = false;
mPushTriggered = false;
}
}
public boolean isToggledOn() {
return mButtonState == ButtonState.ON;
}
public void setToggled(boolean on) {
if (on) {
mButtonState = ButtonState.ON;
mBitmap = mOnBitmap;
} else {
mButtonState = ButtonState.OFF;
mBitmap = mOffBitmap;
}
}
#Override
public void draw(ElapsedTime elapsedTime, IGraphics2D graphics2D,
LayerViewport layerViewport, ScreenViewport screenViewport) {
// Assumed to be in screen space so just draw the whole thing
drawScreenRect.set((int) (position.x - mBound.halfWidth),
(int) (position.y - mBound.halfWidth),
(int) (position.x + mBound.halfWidth),
(int) (position.y + mBound.halfHeight));
graphics2D.drawBitmap(mBitmap, null, drawScreenRect, null);
}
}
Settings menu
public class SettingsMenu extends GameScreen {
private ToggleButtonSound mToggleButtonSound;
public SettingsMenu(Game game) {
super("Settings Menu", game);
mSoundManager = new SoundManager(game);
mMenuScreen = new MenuScreen(game);
music = new MusicManager(game);
AssetStore assetManager = mGame.getAssetManager();
assetManager.loadAndAddBitmap("offswitch", "img/offswitch.png");
assetManager.loadAndAddBitmap("onswitch", "img/onswitch.png");
assetManager.loadAndAddBitmap("SoundOn", "img/Soundon.png");
assetManager.loadAndAddBitmap("SoundOff", "img/Soundoff.png");
assetManager.loadAndAddBitmap("SettingsBackground", "img/settingsbackground.png");
//Load in sound
assetManager.loadAndAddSound("mouseClick", "Sounds/clicksound.wav");
assetManager.loadAndAddMusic("BackgroundMusic", "Sounds/MenuScreenBackgroundMusic.mp3");
//initialise sound
int spacingX = mGame.getScreenWidth() / 3;
int spacingY = mGame.getScreenHeight() / 9;
mPlayButtonBound = new Rect(spacingX, 3 * spacingY, 2 * spacingX, 4 * spacingY);
mInventoryButtonBound = new Rect(spacingX, 5 * spacingY, 2 * spacingX, 6 * spacingY);
soundButtonBound = new Rect(game.getScreenWidth() / 100, game.getScreenWidth() / 100, game.getScreenWidth() / 10, game.getScreenWidth() / 10);
mSettingsBackground = new Rect(1, 1, game.getScreenWidth(), game.getScreenHeight());
mLayerViewport = new LayerViewport(0, 0, game.getScreenWidth(), game.getScreenHeight());
mScreenViewport = new ScreenViewport(0, 0, game.getScreenWidth(), game.getScreenHeight());
int toggleHeight = mGame.getScreenHeight()/3;
mToggleButtonMusic = new ToggleButtonMusic(game.getScreenWidth() / 100, game.getScreenWidth() / 200, game.getScreenWidth() / 10, game.getScreenWidth() / 20, "onswitch","offswitch","onswitch","offswitch", this, mGame);
mToggleButtonSound = new ToggleButtonSound(game.getScreenWidth() / 100, game.getScreenWidth() / 200, game.getScreenWidth() / 10, game.getScreenWidth() / 20, "onswitch","offswitch", this, mGame);
mToggleButtonMusic.setPosition(game.getScreenWidth()/2,game.getScreenHeight()/3);
mToggleButtonSound.setPosition(game.getScreenWidth()/2, toggleHeight*2);
//toggleB.getBitmap();
//toggleB.getBound();
}
private boolean mIsPushed;
#Override
public void update(ElapsedTime elapsedTime) {
music.isPlaying1();
//mToggleButtonSound.setToggled(soundMuted);
mToggleButtonMusic.update(elapsedTime);
mToggleButtonSound.update(elapsedTime);
Input input = mGame.getInput();
List<TouchEvent> touchEvents = input.getTouchEvents();
if (touchEvents.size() > 0) {
TouchEvent touchEvent = touchEvents.get(0);
if (touchEvent.type == TouchEvent.TOUCH_UP) {
if ((soundButtonBound.contains((int) touchEvent.x, (int) touchEvent.y))) {
mGame.getScreenManager().removeScreen("Settings Menu");
mMenuScreen = new MenuScreen(mGame);
mGame.getScreenManager().addScreen(mMenuScreen);
}
}
}
}
#Override
public void draw(ElapsedTime elapsedTime, IGraphics2D graphics2D) {
graphics2D.drawBitmap(mGame.getAssetManager().getBitmap("SettingsBackground"), null, mSettingsBackground, null);
mToggleButtonMusic.draw(elapsedTime,graphics2D,mLayerViewport, mScreenViewport);
mToggleButtonSound.draw(elapsedTime,graphics2D,mLayerViewport, mScreenViewport);
graphics2D.drawBitmap(mGame.getAssetManager().getBitmap("SoundOn"), null, soundButtonBound, null);
}
#Override
public boolean onBackPressed() {
return true;
}
}

Temporary Sprite in Android App

I have an android game where there are sprites moving about the screen. When one is hit, it adds or takes away from the score and then disappears.
What I would like it to do is create a blood splatter when it is hit which will also disappear.
I have actually achieved this but the blood splatter doesn't appear where the sprite was hit. It always goes to the bottom right-hand corner. I was wondering if there is anyone out there that can see where my problem is.
I have a TempSprite class just for the blood splatter and this is below:
public class TempSprite {
private float x;
private float y;
private Bitmap bmp;
private int life = 12;
private List<TempSprite> temps;
public TempSprite(List<TempSprite> temps, GameView gameView, float x,
float y, Bitmap bmp) {
this.x = Math.min(Math.max(x - bmp.getWidth() / 2, 0),
gameView.getWidth() - bmp.getWidth());
this.y = Math.min(Math.max(y - bmp.getHeight() / 2, 0),
gameView.getHeight() - bmp.getHeight());
this.bmp = bmp;
this.temps = temps;
}
public void onDraw(Canvas canvas) {
update();
canvas.drawBitmap(bmp, x, y, null);
}
private void update() {
if (--life < 1) {
temps.remove(this);
}
}
}
All the other code is in the GameView class, specifically in the doDraw and GameView methods:
public class GameView extends SurfaceView implements SurfaceHolder.Callback {
private final Bitmap bmpBlood;
/* Member (state) fields */
private GameLoopThread gameLoopThread;
private Paint paint; //Reference a paint object
/** The drawable to use as the background of the animation canvas */
private Bitmap mBackgroundImage;
// For creating the game Sprite
private Sprite sprite;
private BadSprite badSprite;
// For recording the number of hits
private int hitCount;
// For displaying the highest score
private int highScore;
// To track if a game is over
private boolean gameOver;
// To play sound
private SoundPool mySound;
private int zapSoundId;
private int screamSoundId;
// For multiple sprites
private ArrayList<Sprite> spritesArrayList;
private ArrayList<BadSprite> badSpriteArrayList;
// For the temp blood image
private List<TempSprite> temps = new ArrayList<TempSprite>();
//int backButtonCount = 0;
private void createSprites() {
// Initialise sprite object
spritesArrayList = new ArrayList<>();
badSpriteArrayList = new ArrayList<>();
for (int i = 0; i < 20; i++) {
spritesArrayList.add(new Sprite(this));
badSpriteArrayList.add(new BadSprite(this));
}
}
public GameView(Context context) {
super(context);
// Focus must be on GameView so that events can be handled.
this.setFocusable(true);
// For intercepting events on the surface.
this.getHolder().addCallback(this);
// Background image added
mBackgroundImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.castle);
// Populate multiple sprites
//createSprites();
//Vibrator vibe = (Vibrator) sprite.getSystemService(Context.VIBRATOR_SERVICE);
//vibe.vibrate(500);
// For the temp blood splatter
bmpBlood = BitmapFactory.decodeResource(getResources(), R.drawable.blood1);
//Sound effects for the sprite touch
mySound = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
screamSoundId = mySound.load(context, R.raw.scream, 1);
zapSoundId = mySound.load(context, R.raw.zap, 1);
}
/* Called immediately after the surface created */
public void surfaceCreated(SurfaceHolder holder) {
createSprites();
// We can now safely setup the game start the game loop.
ResetGame();//Set up a new game up - could be called by a 'play again option'
mBackgroundImage = Bitmap.createScaledBitmap(mBackgroundImage, getWidth(), getHeight(), true);
gameLoopThread = new GameLoopThread(this.getHolder(), this);
gameLoopThread.running = true;
gameLoopThread.start();
}
// For the countdown timer
private long startTime; // Timer to count down from
private final long interval = 1 * 1000; // 1 sec interval
private CountDownTimer countDownTimer; // Reference to the class
private boolean timerRunning = false;
private String displayTime; // To display the time on the screen
//To initialise/reset game
private void ResetGame(){
/* Set paint details */
paint = new Paint();
paint.setColor(Color.WHITE);
paint.setTextSize(20);
sprite = new Sprite(this);
hitCount = 0;
// Set timer
startTime = 10; // Start at 10s to count down
// Create new object - convert startTime to milliseconds
countDownTimer = new MyCountDownTimer(startTime*1000, interval);
countDownTimer.start(); // Start the time running
timerRunning = true;
gameOver = false;
}
// Countdown Timer - private class
private class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer (long startTime, long interval) {
super(startTime, interval);
}
public void onFinish() {
//displayTime = "Time is up!";
timerRunning = false;
countDownTimer.cancel();
gameOver = true;
}
public void onTick (long millisUntilFinished) {
displayTime = " " + millisUntilFinished / 1000;
}
}
//This class updates and manages the assets prior to drawing - called from the Thread
public void update(){
}
/**
* To draw the game to the screen
* This is called from Thread, so synchronisation can be done
*/
#SuppressWarnings("ResourceAsColor")
public void doDraw(Canvas canvas) {
canvas.drawBitmap(mBackgroundImage, 0, 0, null);
if (!gameOver) {
sprite.draw(canvas);
//paint.setColor(R.color.red);
canvas.drawText("Time Remaining: " + displayTime, 35, 50, paint);
canvas.drawText("Number of hits: " + hitCount, 35, 85, paint);
// Draw the blood splatter
for (int i = temps.size() - 1; i >= 0; i--) {
temps.get(i).onDraw(canvas);
}
// Draw all the objects on the canvas
for (int i = 0; i < spritesArrayList.size(); i++) {
Sprite sprite = spritesArrayList.get(i);
sprite.draw(canvas);
}
for (int i = 0; i < badSpriteArrayList.size(); i++) {
BadSprite badSprite = badSpriteArrayList.get(i);
badSprite.draw(canvas);
}
} else {
canvas.drawText("Game Over!", 35, 50, paint);
canvas.drawText("Your score was: " + hitCount, 35, 80, paint);
canvas.drawText("To go back home,", 280, 50, paint);
canvas.drawText("press the 'back' key", 280, 70, paint);
}
}
//To be used if we need to find where screen was touched
public boolean onTouchEvent(MotionEvent event) {
for (int i = spritesArrayList.size()-1; i>=0; i--) {
Sprite sprite = spritesArrayList.get(i);
if (sprite.wasItTouched(event.getX(), event.getY())) {
mySound.play(zapSoundId, 1.0f, 1.0f, 0,0, 1.5f);
spritesArrayList.remove(sprite);
//temps.add(new TempSprite(temps, this, x, y, bmpBlood));
hitCount--;
return super.onTouchEvent(event);
}
for (int i1 = badSpriteArrayList.size()-1; i1>=0; i1--) {
BadSprite badSprite = badSpriteArrayList.get(i1);
if (badSprite.wasItTouched(event.getX(), event.getY())) {
mySound.play(screamSoundId, 1.0f, 1.0f, 0, 0, 1.5f);
badSpriteArrayList.remove(badSprite);
temps.add(new TempSprite(temps, this, x, y, bmpBlood));
hitCount++;
return super.onTouchEvent(event);
}
}
}
//else {
return true;
// }
}
public void surfaceDestroyed(SurfaceHolder holder) {
gameLoopThread.running = false;
// Shut down the game loop thread cleanly.
boolean retry = true;
while(retry) {
try {
gameLoopThread.join();
retry = false;
} catch (InterruptedException e) {}
}
}
public int getHitCount() {
return hitCount;
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
}
As always, any help greatly appreciated.
Thanks
This was solved with the following code:
public class TempSprite {
private float x;
private float y;
private Bitmap bmp;
private int life = 12;
private List<TempSprite> temps;
public TempSprite(List<TempSprite> temps, GameView gameView, float x,
float y, Bitmap bmp) {
/*this.x = Math.min(Math.max(x - bmp.getWidth() / 2, 0),
gameView.getWidth() - bmp.getWidth());
this.y = Math.min(Math.max(y - bmp.getHeight() / 2, 0),
gameView.getHeight() - bmp.getHeight());*/
this.x = x;
this.y = y;
this.bmp = bmp;
this.temps = temps;
}
public void onDraw(Canvas canvas) {
update();
canvas.drawBitmap(bmp, x, y, null);
}
private void update() {
if (--life < 1) {
temps.remove(this);
}
}
}
You can see where the commented out sections are and below are what they were replaced with. I was trying to make things a little too complicated.

Libgdx Jiggering Sprite Movement

I recently got into LibGDX using the book "LibGDX Game Development By Example" (Pretty good one btw) and have been playing around with the tutorial projects for the last month.
One of these games is a FlappyBird-clone (of course it is) and I decided to add features, change sprites etc.
Now the problem is that the normal obstacle graphics (flowers) don't fit the new theme and need to be exchanged.
Doing so results in jiggering graphics for the new sprites.
I should point out that the code used to visualize these obstacles has not changed at all, simply exchanging the sprites causes this problem.
I tried a lot of different sprites and all that are not identical to the flowers seem to have this problem.
So whatever is the cause, the old flower sprites are unaffected, every other sprite is.
On to the code (Removed some Getters/Setters and other unrelated methods)
The Flower/Obstacle Class:
public class Flower
{
private static final float COLLISION_RECTANGLE_WIDTH = 13f;
private static final float COLLISION_RECTANGLE_HEIGHT = 447f;
private static final float COLLISION_CIRCLE_RADIUS = 33f;
private float x = 0;
private float y = 0;
private static final float MAX_SPEED_PER_SECOND = 100f;
public static final float WIDTH = COLLISION_CIRCLE_RADIUS * 2;
private static final float HEIGHT_OFFSET = -400.0f;
private static final float DISTANCE_BETWEEN_FLOOR_AND_CEILING = 225.0f;
private final Circle floorCollisionCircle;
private final Rectangle floorCollisionRectangle;
private final Circle ceilingCollisionCircle;
private final Rectangle ceilingCollisionRectangle;
private boolean pointClaimed = false;
private final TextureRegion floorTexture;
private final TextureRegion ceilingTexture;
float textureX,textureY;
public Flower(TextureRegion floorTexture, TextureRegion ceilingTexture)
{
this.floorTexture = floorTexture;
this.ceilingTexture = ceilingTexture;
this.y = MathUtils.random(HEIGHT_OFFSET);
this.floorCollisionRectangle = new Rectangle(x,y,COLLISION_RECTANGLE_WIDTH,COLLISION_RECTANGLE_HEIGHT);
this.floorCollisionCircle = new Circle(x + floorCollisionRectangle.width / 2, y + floorCollisionRectangle.height, COLLISION_CIRCLE_RADIUS);
this.ceilingCollisionRectangle = new Rectangle(x,floorCollisionCircle.y + DISTANCE_BETWEEN_FLOOR_AND_CEILING,COLLISION_RECTANGLE_WIDTH,
COLLISION_RECTANGLE_HEIGHT);
this.ceilingCollisionCircle = new Circle(x + ceilingCollisionRectangle.width / 2, ceilingCollisionRectangle.y, COLLISION_CIRCLE_RADIUS);
}
public void update(float delta)
{
setPosition(x - (MAX_SPEED_PER_SECOND * delta));
}
public void setPosition(float x)
{
this.x = x;
updateCollisionCircle();
updateCollisionRectangle();
}
private void updateCollisionCircle()
{
floorCollisionCircle.setX(x + floorCollisionRectangle.width / 2);
ceilingCollisionCircle.setX(x + ceilingCollisionRectangle.width / 2);
}
private void updateCollisionRectangle()
{
floorCollisionRectangle.setX(x);
ceilingCollisionRectangle.setX(x);
}
public void draw(SpriteBatch batch)
{
drawFloorFlower(batch);
drawCeilingFlower(batch);
}
private void drawFloorFlower(SpriteBatch batch)
{
textureX = floorCollisionCircle.x - floorTexture.getRegionWidth() / 2;
textureY = floorCollisionRectangle.getY() + COLLISION_CIRCLE_RADIUS;
batch.draw(floorTexture,textureX,textureY);
}
private void drawCeilingFlower(SpriteBatch batch)
{
textureX = ceilingCollisionCircle.x - ceilingTexture.getRegionWidth() / 2;
textureY = ceilingCollisionRectangle.getY() - COLLISION_CIRCLE_RADIUS;
batch.draw(ceilingTexture,textureX, textureY);
}
}
And the GameScreen/Main Class:
public class GameScreen extends ScreenAdapter
{
private static final float WORLD_WIDTH = 480;
private static final float WORLD_HEIGHT = 640;
private java.util.prefs.Preferences prefs;
private int highscore;
FlappeeBeeGame flappeeBeeGame;
private ShapeRenderer shapeRenderer;
private Viewport viewport;
private Camera camera;
private SpriteBatch batch;
private Flappee flappee;
private Flower flower;
private Array<Flower> flowers = new Array<Flower>();
private static final float GAP_BETWEEN_FLOWERS = 200.0f;
private boolean gameOver = false;
int score = 0;
BitmapFont bitmapFont;
GlyphLayout glyphLayout;
private TextureRegion background;
private TextureRegion flowerBottom;
private TextureRegion flowerTop;
private TextureRegion bee;
private TextureRegion smallCloud;
private TextureRegion lowCloud;
private Music music_background;
TextureAtlas textureAtlas;
List<Cloud> activeClouds = new ArrayList<Cloud>();
List<Cloud> cloudBarriers = new ArrayList<Cloud>();
private float cloud_minScale = 0.6f;
private float cloud_maxScale = 1.0f;
private float cloud_minY, cloud_maxY;
private float cloud_minDis, cloud_maxDis;
private float cloud_minSpeed = 17.0f;
private float cloud_maxSpeed = 27.0f;
private final float barrierCloud_speed = 150.0f;
private boolean inputBlocked = false;
private float blockTime = 0.5f;
private float remainingblockTime = blockTime;
public GameScreen(FlappeeBeeGame fpg)
{
flappeeBeeGame = fpg;
flappeeBeeGame.getAssetManager().load("assets/flappee_bee_assets.atlas",TextureAtlas.class);
flappeeBeeGame.getAssetManager().finishLoading();
textureAtlas = flappeeBeeGame.getAssetManager().get("assets/flappee_bee_assets.atlas");
prefs = java.util.prefs.Preferences.userRoot().node(this.getClass().getName());
highscore = prefs.getInt("highscore",0);
music_background = Gdx.audio.newMusic(Gdx.files.internal("assets/backgroundmusic.ogg"));
music_background.setLooping(true);
music_background.setVolume(0.5f);
music_background.play();
}
private void createNewFlower()
{
Flower newFlower = new Flower(flowerBottom,flowerTop);
newFlower.setPosition(WORLD_WIDTH + Flower.WIDTH);
flowers.add(newFlower);
}
private void checkIfNewFlowerIsNeeded()
{
if(flowers.size == 0)
{
createNewFlower();
}
else
{
Flower flower = flowers.peek();
if(flower.getX() < WORLD_WIDTH - GAP_BETWEEN_FLOWERS)
{
createNewFlower();
}
}
}
private void drawFlowers()
{
for(Flower flower : flowers)
{
flower.draw(batch);
}
}
private void removeFlowersIfPassed()
{
if(flowers.size > 0)
{
Flower firstFlower = flowers.first();
if(firstFlower.getX() < -Flower.WIDTH)
{
flowers.removeValue(firstFlower,true);
}
}
}
#Override
public void resize(int width, int height) {
super.resize(width, height);
viewport.update(width,height);
}
#Override
public void show() {
super.show();
camera = new OrthographicCamera();
camera.position.set(WORLD_WIDTH / 2, WORLD_HEIGHT / 2, 0);
camera.update();
viewport = new FitViewport(WORLD_WIDTH,WORLD_HEIGHT, camera);
shapeRenderer = new ShapeRenderer();
batch = new SpriteBatch();
bitmapFont = new BitmapFont(Gdx.files.internal("assets/score_new.fnt"));
glyphLayout = new GlyphLayout();
background = textureAtlas.findRegion("bg");
flowerBottom = textureAtlas.findRegion("pipeBottom");
flowerTop = textureAtlas.findRegion("flowerTop");
bee = textureAtlas.findRegion("bee");
smallCloud = textureAtlas.findRegion("smallCloud");
lowCloud = textureAtlas.findRegion("lowerCloud");
flower = new Flower(flowerBottom,flowerTop);
flappee = new Flappee(bee,textureAtlas);
flappee.setPosition(WORLD_WIDTH/4,WORLD_HEIGHT/2);
cloud_minDis = smallCloud.getRegionWidth() / 4;
cloud_maxDis = smallCloud.getRegionWidth();
cloud_maxY = viewport.getWorldHeight() - smallCloud.getRegionHeight()/2;
cloud_minY = viewport.getWorldHeight() - smallCloud.getRegionHeight() * 2;
Cloud a = generateCloud(null);
Cloud b = generateCloud(a);
Cloud c = generateCloud(b);
Cloud d = generateCloud(c);
Cloud e = generateCloud(d);
activeClouds.add(a);
activeClouds.add(b);
activeClouds.add(c);
activeClouds.add(d);
activeClouds.add(e);
a = new Cloud(lowCloud,batch,0,0 - lowCloud.getRegionHeight()/4,barrierCloud_speed,1.0f);
b = new Cloud(lowCloud,batch,lowCloud.getRegionWidth(),0 - lowCloud.getRegionHeight()/4,barrierCloud_speed,1.0f);
c = new Cloud(lowCloud,batch,lowCloud.getRegionWidth()*2,0 - lowCloud.getRegionHeight()/4,barrierCloud_speed,1.0f);
cloudBarriers.add(a);
cloudBarriers.add(b);
cloudBarriers.add(c);
}
public Cloud generateCloud(Cloud formerCloud)
{
Cloud d;
if(formerCloud == null)
{
float randomVal = (float)Math.random();
d = new Cloud(smallCloud,batch,viewport.getWorldWidth(),
(float)Math.random() * (cloud_maxY - cloud_minY) + cloud_minY,
randomVal * (cloud_maxSpeed-cloud_minSpeed) + cloud_minSpeed,
randomVal * (cloud_maxScale-cloud_minScale) + cloud_minScale);
return d;
}
float randomVal = (float)Math.random();
d = new Cloud(smallCloud,batch,formerCloud.getPosX() + ((float)
Math.random() * (cloud_maxDis - cloud_minDis) + cloud_minDis),(float)Math.random() * (cloud_maxY - cloud_minY) + cloud_minY,
randomVal * (cloud_maxSpeed-cloud_minSpeed) + cloud_minSpeed,
randomVal * (cloud_maxScale-cloud_minScale) + cloud_minScale);
return d;
}
#Override
public void render(float delta) {
super.render(delta);
clearScreen();
shapeRenderer.setProjectionMatrix(camera.projection);
shapeRenderer.setTransformMatrix(camera.view);
shapeRenderer.begin(ShapeRenderer.ShapeType.Line);
shapeRenderer.end();
draw(delta);
update(delta);
}
private void draw(float delta)
{
batch.setProjectionMatrix(camera.projection);
batch.setTransformMatrix(camera.view);
batch.begin();
batch.draw(background,0,0);
drawClouds(delta);
drawScore();
drawFlowers();
//drawDebug();
if(!gameOver)
{
flappee.draw(batch,delta);
}
drawBarrierClouds(delta);
batch.end();
}
private void updateClouds(float delta)
{
boolean move = false;
Cloud tmp = null;
for(Cloud c : cloudBarriers)
{
c.update(delta);
if(c.getPosX() <= -lowCloud.getRegionWidth())
{
tmp = c;
move = true;
}
}
if(move)
{
float positionX = cloudBarriers.get(cloudBarriers.size()-1).getPosX() + lowCloud.getRegionWidth();
if(positionX < viewport.getWorldWidth())
{
positionX = viewport.getWorldWidth();
}
tmp.setPos(positionX,0 - lowCloud.getRegionHeight()/4);
cloudBarriers.remove(tmp);
cloudBarriers.add(tmp);
tmp = null;
move = false;
}
for(Cloud c : activeClouds)
{
c.update(delta);
if(c.getPosX() <= -smallCloud.getRegionWidth())
{
tmp = c;
move = true;
}
}
if(move)
{
float randomVal = (float)Math.random();
float positionX = activeClouds.get(activeClouds.size()-1).getPosX() + ((float)
Math.random() * (cloud_maxDis - cloud_minDis) + cloud_minDis);
if(positionX < viewport.getWorldWidth())
{
positionX = viewport.getWorldWidth();
}
tmp.setPos(positionX,(float)Math.random() * (cloud_maxY - cloud_minY) + cloud_minY);
tmp.setSpeed(randomVal * (cloud_maxSpeed - cloud_minSpeed) + cloud_minSpeed);
tmp.setScale(randomVal * (cloud_maxScale - cloud_minScale) + cloud_minScale);
activeClouds.remove(tmp);
activeClouds.add(tmp);
move = false;
tmp = null;
}
}
private void drawBarrierClouds(float delta)
{
for(Cloud c : cloudBarriers)
{
c.render();
}
}
private void drawClouds(float delta)
{
for(Cloud c : activeClouds)
{
c.render();
}
}
private void clearScreen()
{
Gdx.gl.glClearColor(Color.BLACK.r,Color.BLACK.g,Color.BLACK.b, Color.BLACK.a);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
private void blockFlappeeLeavingTheWorld()
{
flappee.setPosition(flappee.getX(), MathUtils.clamp(flappee.getY(),0,WORLD_HEIGHT));
}
private void updateFlowers(float delta)
{
for(Flower flower : flowers)
{
flower.update(delta);
}
checkIfNewFlowerIsNeeded();
removeFlowersIfPassed();
}
private void update(float delta)
{
updateClouds(delta);
if(!gameOver) {
updateFlappee(delta);
updateFlowers(delta);
updateScore();
if (checkForCollision())
{
gameOver = true;
inputBlocked = true;
remainingblockTime = blockTime;
restart();
}
}
else
{
if((Gdx.input.isKeyJustPressed(Input.Keys.SPACE) || Gdx.input.isButtonPressed(Input.Buttons.LEFT)) && !inputBlocked)
{
gameOver = false;
score = 0;
}
if(inputBlocked)
{
if(remainingblockTime > 0)
{
remainingblockTime -= delta;
}
else
{
inputBlocked = false;
remainingblockTime = blockTime;
}
}
}
}
private void restart()
{
flappee.setPosition(WORLD_WIDTH / 4, WORLD_HEIGHT / 2);
flowers.clear();
}
#Override
public void dispose() {
super.dispose();
}
private boolean checkForCollision()
{
for(Flower flower : flowers)
{
if(flower.isFlappeeColliding(flappee))
{
if(score > highscore)
{
highscore = score;
prefs.putInt("highscore",highscore);
inputBlocked = true;
remainingblockTime = blockTime;
}
return true;
}
}
return false;
}
}
I'd love to give you a runnable jar but I've got some problems building a working version. Let's just say a jar is out of the question for now.
What I can give you are screenshots:
Jiggering Sprite View
Functional Flower Sprite View
The first image shows the problem: The new sprites (which are just debug) become edgy like the top of the sprite can't compete with the speed of its lower half.
The second image shows the old sprites for comparison: They don't show any of this behaviour, even if they are longer than the one on the screenshot.
So what do you people think?
What causes this behaviour and how should I fix it?
Thanks in advance for any help, I appreciate it :)
Greetz!
EDIT:
I kind of fixed it.
When switching to another computer and running the game the issue didn't come up anymore.
Specifically I went from Debian to Windows 10 and from NVIDIA Optimus to a standard desktop AMD-Card.
If you should encounter this problem try another PC with a different OS and/or GPU.
Sadly (if you were to google this question) I can't tell you how to solve it on the first machine or what exactly caused it, but at least it shouldn't come up on anyone else's computer when you send them your project.

LibGDX Player only faces left and movement isn't animated

I am working on a game in LibGDX and both my players direction and walking animation won't change. He can walk up, down, left, and right, but only faces left no matter what direction he's walking.
public class WorldController {
enum KeyBinds {
LEFT, RIGHT, UP, DOWN, JUMP, FIRE
}
private World world;
private Player p;
static Map<KeyBinds, Boolean> keys = new HashMap<WorldController.KeyBinds, Boolean>();
static {
keys.put(KeyBinds.LEFT, false);
keys.put(KeyBinds.RIGHT, false);
keys.put(KeyBinds.UP, false);
keys.put(KeyBinds.DOWN, false);
keys.put(KeyBinds.JUMP, false);
keys.put(KeyBinds.FIRE, false);
};
public WorldController(World world) {
this.world = world;
this.p = world.getPlayer();
}
// ** Key presses and touches **************** //
public void leftPressed() {
keys.get(keys.put(KeyBinds.LEFT, true));
}
public void rightPressed() {
keys.get(keys.put(KeyBinds.RIGHT, true));
}
public void upPressed() {
keys.get(keys.put(KeyBinds.UP, true));
}
public void downPressed() {
keys.get(keys.put(KeyBinds.DOWN, true));
}
public void jumpPressed() {
keys.get(keys.put(KeyBinds.JUMP, true));
}
public void firePressed() {
keys.get(keys.put(KeyBinds.FIRE, false));
}
public void leftReleased() {
keys.get(keys.put(KeyBinds.LEFT, false));
}
public void rightReleased() {
keys.get(keys.put(KeyBinds.RIGHT, false));
}
public void upReleased() {
keys.get(keys.put(KeyBinds.UP, false));
}
public void downReleased() {
keys.get(keys.put(KeyBinds.DOWN, false));
}
public void jumpReleased() {
keys.get(keys.put(KeyBinds.JUMP, false));
}
public void fireReleased() {
keys.get(keys.put(KeyBinds.FIRE, false));
}
/** The main update method **/
public void update(float delta) {
processInput();
p.update(delta);
}
/** Change player's state and parameters based on input controls **/
private void processInput() {
if(Gdx.input.isKeyPressed(Keys.LEFT)) {
// left is pressed
//p.setFacingLeft(true);
p.setState(State.WALKING);
p.getVelocity().x = -Player.SPEED;
p.getVelocity().y = 0;
}
if(Gdx.input.isKeyPressed(Keys.RIGHT)){
// right is pressed
//p.setFacingRight(true);
p.setState(State.WALKING);
p.getVelocity().x = Player.SPEED;
p.getVelocity().y = 0;
}
if(Gdx.input.isKeyPressed(Keys.UP)) {
// up is pressed
//p.setFacingUp(true);
p.setState(State.WALKING);
p.getVelocity().y = Player.SPEED;
p.getVelocity().x = 0;
}
if(Gdx.input.isKeyPressed(Keys.DOWN)) {
// down is pressed
//p.setFacingDown(true);
p.setState(State.WALKING);
p.getVelocity().y = -Player.SPEED;
p.getVelocity().x = 0;
}
// need to check if both or none direction are pressed, then player is idle
// if ((keys.get(Keys.LEFT) && keys.get(Keys.RIGHT)) ||
// (!keys.get(Keys.LEFT) && !(keys.get(Keys.RIGHT)))) {
// p.setState(State.IDLE);
// // acceleration is 0 on the x
// p.getAcceleration().x = 0;
// // horizontal speed is 0
// p.getVelocity().x = 0;
// }
}
}
public class WorldRenderer {
private static final float CAMERA_WIDTH = 10f;
private static final float CAMERA_HEIGHT = 7f;
private World world;
private OrthographicCamera cam;
/** for debug rendering **/
ShapeRenderer debugRenderer = new ShapeRenderer();
private SpriteBatch spriteBatch;
private boolean debug = false;
private int width;
private int height;
private float ppuX;
private float ppuY;
private static final float RUNNING_FRAME_DURATION = 0.06f;
/** Textures **/
private TextureRegion pIdleLeft;
private TextureRegion pIdleRight;
private TextureRegion pIdleUp;
private TextureRegion pIdleDown;
private TextureRegion blockTexture;
private TextureRegion pFrame;
/** Animations **/
private Animation walkLeftAnimation;
private Animation walkRightAnimation;
private Animation walkUpAnimation;
private Animation walkDownAnimation;
private void loadTextures() {
TextureAtlas atlas = new TextureAtlas(Gdx.files.internal("images/textures/textures.pack"));
pIdleLeft = atlas.findRegion("Left1");
pIdleRight = new TextureRegion(pIdleLeft);
pIdleRight.flip(true, false);
pIdleUp = atlas.findRegion("Back1");
pIdleDown = atlas.findRegion("Front1");
blockTexture = atlas.findRegion("stone");
//Walking Left Animation
TextureRegion[] walkLeftFrames = new TextureRegion[2];
walkLeftFrames[0] = atlas.findRegion("Left1");
walkLeftFrames[1] = atlas.findRegion("Left2");
walkLeftAnimation = new Animation(RUNNING_FRAME_DURATION, walkLeftFrames);
//Walking Right Animation
TextureRegion[] walkRightFrames = new TextureRegion[2];
walkRightFrames[0] = new TextureRegion(walkLeftFrames[0]);
walkRightFrames[0].flip(true, false);
walkRightFrames[1] = new TextureRegion(walkLeftFrames[1]);
walkRightFrames[1].flip(true, false);
walkRightAnimation = new Animation(RUNNING_FRAME_DURATION, walkRightFrames);
//Walking Up Animation
TextureRegion[] walkUpFrames = new TextureRegion[2];
walkUpFrames[0] = atlas.findRegion("Back1");
walkUpFrames[1] = atlas.findRegion("Back2");
walkUpAnimation = new Animation(RUNNING_FRAME_DURATION, walkUpFrames);
//Walking Down Animation
TextureRegion[] walkDownFrames = new TextureRegion[2];
walkLeftFrames[0] = atlas.findRegion("Front1");
walkLeftFrames[1] = atlas.findRegion("Front2");
walkDownAnimation = new Animation(RUNNING_FRAME_DURATION, walkDownFrames);
}
public void drawPlayer() {
Player p = world.getPlayer();
if(p.getState().equals(State.IDLE)) {
if(Gdx.input.isKeyPressed(Keys.LEFT)) pFrame = pIdleLeft;
else if(Gdx.input.isKeyPressed(Keys.RIGHT)) pFrame = pIdleRight;
else if(Gdx.input.isKeyPressed(Keys.UP)) pFrame = pIdleUp;
else if(Gdx.input.isKeyPressed(Keys.DOWN)) pFrame = pIdleDown;
}
if(p.getState().equals(State.WALKING)) {
if(Gdx.input.isKeyPressed(Keys.LEFT)) walkLeftAnimation.getKeyFrame(p.getStateTime(), true);
else if(Gdx.input.isKeyPressed(Keys.RIGHT)) walkRightAnimation.getKeyFrame(p.getStateTime(), true);
else if(Gdx.input.isKeyPressed(Keys.UP)) walkUpAnimation.getKeyFrame(p.getStateTime(), true);
else if(Gdx.input.isKeyPressed(Keys.DOWN)) walkDownAnimation.getKeyFrame(p.getStateTime(), true);
}
spriteBatch.draw(pFrame, p.getXPosition() * ppuX, p.getYPosition() * ppuY, Player.SIZE * ppuX, Player.SIZE * ppuY);
}
public void setSize(int w, int h){
this.width = w;
this.height = h;
ppuX = (float)width / CAMERA_WIDTH;
ppuY = (float)height / CAMERA_HEIGHT;
}
public WorldRenderer(World world, boolean debug) {
this.world = world;
this.cam = new OrthographicCamera(CAMERA_WIDTH, CAMERA_HEIGHT);
this.cam.position.set(CAMERA_WIDTH / 2f, CAMERA_HEIGHT / 2f, 0);
this.cam.update();
this.debug = debug;
spriteBatch = new SpriteBatch();
loadTextures();
}
public void render(){
spriteBatch.begin();
drawBlocks();
drawPlayer();
spriteBatch.end();
if(debug){
drawDebug();
}
}
public void drawBlocks(){
for(Block block : world.getBlocks()){
spriteBatch.draw(blockTexture, block.getXPosition() * ppuX, block.getYPosition() * ppuY, Block.getSize() * ppuX, Block.getSize() * ppuY );
}
}
public void drawDebug() {
// render blocks
debugRenderer.setProjectionMatrix(cam.combined);
debugRenderer.begin(ShapeType.Line);
for (Block block : world.getBlocks()) {
Rectangle rect = block.getBounds();
float x1 = block.getXPosition() + rect.x;
float y1 = block.getYPosition() + rect.y;
debugRenderer.setColor(new Color(1, 0, 0, 1));
debugRenderer.rect(x1, y1, rect.width, rect.height);
}
// render Player
Player p = world.getPlayer();
Rectangle rect = p.getBounds();
float x1 = p.getXPosition() + rect.x;
float y1 = p.getYPosition() + rect.y;
debugRenderer.setColor(new Color(0, 1, 0, 1));
debugRenderer.rect(x1, y1, rect.width, rect.height);
debugRenderer.end();
}
}
public class Player {
public enum State{
IDLE, WALKING, JUMPING, DYING
}
public static final float SPEED = 4f; //units per second
public static final float SIZE = 0.5f; //half a unit
float stateTime = 0;
Vector2 position = new Vector2();
Vector2 acceleration = new Vector2();
Vector2 velocity = new Vector2();
Rectangle bounds = new Rectangle();
State state = State.IDLE;
boolean facingLeft;
boolean facingRight;
boolean facingUp;
boolean facingDown;
public Player(Vector2 position){
this.position = position;
this.bounds.height = SIZE;
this.bounds.width = SIZE;
}
public void setFacingLeft(boolean facingLeft) {
this.facingLeft = facingLeft;
}
public void setFacingRight(boolean facingRight) {
this.facingRight = facingRight;
}
public void setFacingUp(boolean facingUp) {
this.facingUp = facingUp;
}
public void setFacingDown(boolean facingDown) {
this.facingDown = facingDown;
}
public Vector2 getAcceleration() {
return acceleration;
}
public Vector2 getVelocity() {
return velocity;
}
public void setState(State newState){
this.state = newState;
}
public void update(float delta){
stateTime += delta;
position.add(velocity.cpy().scl(delta));
}
public Rectangle getBounds() {
return bounds;
}
public Object getPosition() {
return position;
}
public float getXPosition(){
return this.position.x;
}
public float getYPosition(){
return this.position.y;
}
public Object getState() {
return state;
}
public float getStateTime() {
return stateTime;
}
}
Sorry for all the code but I don't know where the problem is and didn't want to leave out anything relevant. I'm sure it's a silly mistake but I've been starring at it for a long time.
Also, I made an effort to put each class in it's own code block but it wasn't working out, I'm new to stackoverflow. Thanks to anyone who tries to help.

Categories

Resources