AndEngine, PhysicsWorld not updating? - java

I'm not entirely sure what I'm doing wrong. I have written this code multiple times before without problems. The problem is that the physics world just does not seem to be updating and I don't know why! Right now I have a gameScene class which extends a normal scene, this is the onCreate method:
#Override
public void create() {
ParallaxBackground background = new ParallaxBackground(0, 0, 0);
background.attachParallaxEntity(new ParallaxEntity(0, new Sprite(0, 0, res.BasicBackground, res.vbom)));
this.setBackground(background);
test = new Sprite(0, 0, res.GrassRegion, res.vbom);
FixtureDef fix = PhysicsFactory.createFixtureDef(10f, 0f, 10f);
Body bod = PhysicsFactory.createBoxBody(physicsWorld, test, BodyType.DynamicBody, fix);
attachChild(test);
physicsWorld = new PhysicsWorld(new Vector2(SensorManager.GRAVITY_EARTH, SensorManager.GRAVITY_EARTH), false);
physicsWorld.registerPhysicsConnector(new PhysicsConnector(test, bod, true, true));
this.registerUpdateHandler(physicsWorld);
}
(I removed a lot of the unnecessary things) I just have a basic test sprite to make sure that the physics is working (which it is not). The app runs without any errors, its just that the sprite will not move, leading me to think that its a problem with the physics world being update.
As you can see, I'm setting the gravity to be accelerating in both the X and Y directions. I did this because I thought maybe it wasn't working in one direction for some reason. I'm thinking that maybe I have to set the scene to update in the main activity? But I don't remember having to do that with any of my other apps. Any help is appreciated thank you :)

No, this.registerUpdateHandler(physicsWorld); will do just fine. Try adding this:
physicsWorld = new PhysicsWorld(new Vector2(0, AHC.WORLD_GRAVITY), false) {
#Override
public void onUpdate(float pSecondsElapsed) {
super.onUpdate(pSecondsElapsed);
}
};
And put a breakpoint or Log.i(TAG, "hey"); inside onUpdate to check if it hits it
EDIT:
Try registering a "normal" UpdateHandler, you can do it in 2 ways:
public class YourGameActivity implements IUpdateHandler{
...
private void yourSetupMethod(){
registerUpdateHandler(this);
}
#Override
public void reset() {}
#Override
public void onUpdate(float pSecondsElapsed) {
Log.i(TAG, "hey");
}
}
or you can create a class that implements IUpdateHandler and then:
public class YourGameActivity{
private MyClassThatImplementsIUpdateHandler mInstance;
...
private void yourSetupMethod(){
registerUpdateHandler(mInstance);
}
}
It's the same.
Try it and see if it logs something, if for some reason you can't see the log use a breakpoint just to be sure.

Related

Overlapping music in a Java game with LibGDX implementation

I am having a problem in with this part of the code, I am creating a very simple game in Java with the implementation of LibGDX.
I have three different game states that are handled in three different classes:
StateCreation
MenuState
PlayState
They all work perfectly except for one thing. The music that I have inserted and that is created in the StateCreation should start over, when the player gets to the gameover and the state changes the mode to start over or go back to the menu. This does not happen and the music overlaps
public class GameBarbo extends ApplicationAdapter {
//impostazioni base dell'applicazione
public static final int WIDTH = 480;
public static final int HEIGHT = 800;
public static final String TITLE = "Cavaliere";
private GameStateManager gsm = new GameStateManager();
private SpriteBatch batch;
private Music music;
#Override
public void create () {
batch = new SpriteBatch();
music = Gdx.audio.newMusic(Gdx.files.internal("sound.mp3"));
music.setVolume(0.1f);
music.play();
Gdx.gl.glClearColor(1, 0, 0, 1);
gsm.push(new MenuState(gsm));
}
#Override
public void render () {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
gsm.update(Gdx.graphics.getDeltaTime());
gsm.render(batch);
}
#Override
public void dispose() {
super.dispose();
music.dispose();
}
}
You code looks very much like what I found in this guide (though they don't include super.dispose().)
Is it possible that when your game state changes, the dispose() method does not execute? I haven't used libgdx in ages, but it could be the case that dispose() only executes when you exit the program.
I see from this wiki that the Music class has a stop() method. Perhaps that needs to be called directly when the game ends. But IDK if stopping the file and executing a reload for another iteration is asking for a memory leak or not.
Hopefully someone with more experience will answer, but maybe these thoughts will help you figure something out in the meantime.

libGDX Android white screen after back button pressed

I am having a problem with libGDX where when I resume the application after exiting with the back button, I get only a white screen.
The actual app runs, accepts touch input, and plays sounds, but the screen is just white.
I have read that keeping static references to Textures may cause this problem but I am not doing that.
Below is a simplified version of how my asset code works.
public class GdxGame extends Game {
private Assets assets;
#Override
public void onCreate() {
assets = new Asstes();
assets.startLoading();
/*
*Within SplashScreen, GdxGame.getAssets() is accessed, and
*manager.update() is called
*/
setScreen(new SplashScreen());
}
#Override
public void dispose() {
assets.dispose();
assets = null;
}
//Perhaps a problem??
public static Assets getAssets() {
return ((GdxGame) Gdx.app.getApplicationListener()).assets;
}
}
public class Assets implements Disposable{
private AssetManager manager;
public Assets() {
manager = new AssetManager();
}
public void startLoading() {
manager.load(....);
}
#Override
public void dispose() {
manager.dispose();
}
}
Upon returning to the application after the back button is pressed, the AssetManager is recreated, the SplashScreen is reopened (as white), and the AssetManager updates until all assets are reloaded (takes about 2 seconds).
So when the application is reopened, a new AssetManager is loading all of the necessary textures, but for some reason everything is still white.
Could it have something to do with how I access the AssetManager from my UI and Game classes?
//In GdxGame
public Assets getAssets() {
return ((GdxGame) Gdx.app.getApplicationListener()).assets;
}
That is the only place where I could see something going wrong, but even still, I don't understand what could be wrong with that.
Any help would be much appreciated.
Edit:
Here is the SplashScreen class. This makes the issue even more confusing. In the SplashScreen class I load, draw, and dispose a new Texture for the logo. Nothing to do with the AssetManager. Returning after the back button is pressed, this new Texture does not appear either.
public class SplashScreen extends Screen {
private Texture logo;
private Assets assets;
#Override
public void show() {
assets = GdxGame.getAssets();
logo = new Texture(Gdx.files.internal("data/logo.png"));
}
#Override
public void render(float delta) {
super.render(float delta);
if(assets.load()) {
//Switch screens
}
//getBatch() is the same form as getAssets() ((GdxGame) Gdx.app.getApplicationListener()).batch)
GdxGame.getBatch().draw(logo, 100, 100, 250, 250);
}
#Override
public void hide() {
super.hide();
logo.dispose();
}
}
It turns out the issue was to do with how I was managing screens. I had a convenience method in my GdxGame class that allowed me to switch screens based on a ScreenType enum.
Within the enum, I would create a new screen with reflection, given the screen's class in the enum constructor.
The problem is that I stored the screens in the enums, and only created them once. This means that I was keeping and using screens from the old context when I returned after pressing back.
To solve this, I simply had to change it so that a new screen is created every time the enum is accessed, instead of storing one at the start.

Libgdx: SetScreen Issues

Hello the following code is from my main class trying to call another class i made which implements screen.
if (grumpface.whiteballoon.getBoundingRectangle().overlaps(spriterect)) {
System.out.println("hey");
setScreen(new GameOverScreen());
}
;
here is the class i am calling.
class GameOverScreen implements Screen{
private Stage stage;
// Called automatically once for init objects
#Override
public void show() {
stage = new Stage();
float delta = Gdx.graphics.getDeltaTime();
stage.setDebugAll(true); // Set outlines for Stage elements for easy debug
BitmapFont white = new BitmapFont(Gdx.files.internal("hazey.fnt"), false);
LabelStyle headingStyle = new LabelStyle(white, Color.WHITE);
Label gameoverstring = new Label("game ovaaaa!", headingStyle);
gameoverstring.setPosition(100, 100);
stage.addActor(gameoverstring);
}
// Called every frame so try to put no object creation in it
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
System.out.println("hey");
stage.act(delta);
stage.draw();
}
even though i am not returning any stack errors, my program still will not switch screen whenever the event is performed. i can tell the gameoverscreen class is getting called, because whenever the event happens the System.out.println("hey"); is triggered and starts in the console. however, there is no color clear or label drawing like there should be.
Don't use Show() like that. You should initialize your objects in your constructor. maybe try to set screen like that :
((com.badlogic.gdx.Game) Gdx.app.getApplicationListener())
.setScreen(new GameScreen());
We need to see more code to help you
ps i can't comment, but the link : https://code.google.com/p/libgdx-users/wiki/ScreenAndGameClasses is outdated, check it : https://github.com/libgdx/libgdx/wiki

libGDX SpriteCache: transparency on images not displayed properly

I'm developing a Tower Defense game using libGDX. I've just started and I am able to display the path, the "environment" and the enemies walking along the path.
I displayed the environment using a SpriteBatch-Object, like this:
public LevelController(Level level) {
spriteBach = new SpriteBach();
atlas = new TextureAtlas(Gdx.files.internal("images/textures/textures.pack"));
}
public void setSize() {
spriteBatch.setProjectionMatrix(this.cam.combined);
}
public void render() {
spriteBatch.begin();
drawTowerBases();
spriteBatch.end();
}
private void drawTowerBases() {
// for each tower base (=environment square)
TextureRegion towerBaseTexture = atlas.findRegion("TowerBase");
if(towerBaseTexture != null) {
spriteBatch.draw(towerBaseTexture, x, y, 1f, 1f);
}
}
This is working properly and the textures are displayed well: Tower Defense using spriteBatch
Now, I was wondering if it is possible to cache the background. Because it stays the same, there is no need to calculate it every time. I've found the SpriteCache through Google-Search. So I changed the code as follows:
public LevelController(Level Level) {
spriteCache= new SpriteCache();
atlas = new TextureAtlas(Gdx.files.internal("images/textures/textures.pack"));
spriteCache.beginCache();
this.drawTowerBases();
this.spriteCacheEnvironmentId = spriteCache.endCache();
}
public void setSize() {
this.cam.update();
spriteCache.setProjectionMatrix(this.cam.combined);
}
public void render() {
spriteCache.begin();
spriteCache.draw(this.spriteCacheEnvironmentId);
spriteCache.end();
}
private void drawTowerBases() {
// for each tower base (=environment square)
TextureRegion towerBaseTexture = atlas.findRegion("TowerBase");
if(towerBaseTexture != null) {
spriteCache.add(towerBaseTexture, x, y, 1f, 1f);
}
}
And now the game looks like this: Tower Defense using spriteCache
For me it seems as if the transparency is not rendered properly. If I take images without transparency, everything works fine. Does anyone have an idea, why this happens and how I can fix this?
Thank you in advance.
Taken from the SpriteCache documentation:
Note that SpriteCache does not manage blending. You will need to enable blending (Gdx.gl.glEnable(GL10.GL_BLEND);) and set the blend func as needed before or between calls to draw(int).
I guess there is not much more to say.

LibGDX not running render() method

I'm experiencing a problem using LibGDX.
I have a Screen and in its render method I have:
public class LoadingScreen implements Screen{
private OrthographicCamera guiCam;
private TankChallenge tankChallenge;
private SpriteBatch batcher;
private GL10 OpenGL;
public LoadingScreen(TankChallenge tankChallenge) {
this.tankChallenge=tankChallenge;
Gdx.graphics.setTitle("RobotChallange Beta - Loading");
float AR = Gdx.graphics.getHeight()/Gdx.graphics.getWidth();
guiCam = new OrthographicCamera(10,10 * AR);
guiCam.position.set(10f/2,AR*10f/2,0);
batcher = new SpriteBatch();
OpenGL = Gdx.graphics.getGL10();
//loadAssets();
}
#Override
public void render(float delta) {
OpenGL.glClearColor(1, 0.5f, 1, 1);
OpenGL.glClear(GL10.GL_COLOR_BUFFER_BIT);
System.out.print("e");
guiCam.update();
Sprite sp = new Sprite();
sp.setColor(1f,1f,0, 1);
sp.setSize(100,100);
sp.setOrigin(20, 0);
batcher.setProjectionMatrix(guiCam.combined);
batcher.begin();
batcher.disableBlending();
sp.draw(batcher);
batcher.end();
}
I call this by setting it in the implementes ApplicationListener class. I know it is arriving the LoadingScreen because Title is actually set to "RobotChallenge Beta - Loading".
I found a solution for both problems. I added to the Game extending class this:
public void render() {
super.render();
}
Thanks to this the problem is solved and I don't need to override the SetScreen method. Thanks!
Immediately after setting this as your screen, you need to call super.render() in your Game extending class. For instance, I use the following method in my main Game extending class for setting the screen:
#Override
public void setScreen(Screen screen)
{
super.setScreen(screen);
super.render();
}
This seems to kick off render() being called.
Just remove #Override render() in your Game extending class, that fixes the problem. Overriding setScreen method causes flickering you mentioned.

Categories

Resources