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.
Related
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.
i'm making a game in libgdx but i'm new and i donĀ“t know if my code is the correct form or the best way to do it.
i'm trying to make the basis of the game:
a screen manager to implement a Menu,
an option screen
a loading screen
a game screen
a pause Screem
a game over screen
In the loading screen I like to do something like Dragon Ball when the loading screen allow us to make goku eat rice, the pause screen needs to draw some statistics and options something like Megaman or Castlevania, the menu do something when the player touch a button something like move the camera or open a door, or move to another "scenario" showing another options, and the game over screen needs to previously gives the player the opportunity to win some life to not lose the game.
I try to make this in this form:
I have the main class of the game with the constructor, and the overriden metods create(), render(), resize() and dispose(), the variables for a camera, a viewport, a Spritebatch, a int to store the current screen, and a manager for the screens.
public class BOS_Project extends Game {
OrthographicCamera camera;
Viewport viewport;
SpriteBatch batch;
AssetManager manager = new AssetManager();
int actualScreen = 0;
public BOS_Project(){
camera = new OrthographicCamera();
camera.setToOrtho(false, screenWidth, screenHeight);
viewport = new FitViewport(screenWidth, screenHeight);
}
#Override
public void create(){
batch = new SpriteBatch();
}
#Override
public void render(){
actualScreen = 1;
ScreenManager.getInstance().showScreen(1, this);
super.render();
}
#Override
public void resize(int width, int height){
viewport.update(width, height);
}
#Override
public void dispose(){
batch.dispose();
}
}
Also the class ScreenManager is singleton, and
public class ScreenManager{
private static ScreenManager instance;
private Game game;
Screen screen;
private ScreenManager(){
super();
}
public static ScreenManager getInstance(){
if(instance == null){
instance = new ScreenManager();
}
return instance;
}
public void initialize(Game game){
this.game = game;
}
public void showScreen(int currentscreen, BOS_Project game){
if(currentscreen == 1){
if(screen!=null)
screen.dispose();
screen = new LoadingScreen(game, game.actualScreen);
game.setScreen(screen);
}else if(currentscreen == 2){
if(screen!=null)
screen.dispose();
screen = new GameScreen(game);
game.setScreen(screen);
}else{
if(screen!=null)
screen.dispose();
screen = new MenuScreen(game);
game.setScreen(screen);
}
}
The other classes are the MenuScreen, GameScreen and Loading Screen.
Loading Screen:
public LoadingScreen(BOS_Project game2, int screen2){
game = game2;
screen = screen2;
game.manager.load("button.png", Texture.class);
game.manager.finishLoadingAsset("button.png");
sprite1 = new Sprite(game.manager.get("button.png", Texture.class));
sprite1.setPosition(0, 0);
//This is a method to load the assets for the especific screen
game.load(screen);
}
#Override
public void render(float delta){
if(game.manager.getProgress()==1) {
if (time < 3) {
Gdx.app.log("Loading: ", "90.0");
}
}else {
Gdx.app.log("Loading: ", String.valueOf(game.manager.getProgress() * 100));
}
game.manager.update();
batch = game.batch;
Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
sprite1.draw(batch);
if(game.manager.getProgress()==1 && time > 3){
if(screen==1) {
ScreenManager.getInstance().showScreen(2, game);
}else{
ScreenManager.getInstance().showScreen(3, game);
}
}else{
time += delta;
}
batch.end();
super.render(delta);
}
The Menu and Game classes are similar to loading, only call the assets and draw some sprite on the render method.
This code function well to change screens but I don't know if is the correct form, and another big question is how to manage the pause screen, because I manage this only storing a variable if the variable is pause the render method draw something, if not draw the normal game, but if I want to change the options and images of the pause I need to check variables to know what the pause needs to draw.
if(pause){
Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
spritePause.draw(batch);
batch.end();
}else if(game){
batch.begin();
spriteGame.draw(batch);
batch.end();
}
So, am i doing it right? or what would you recommend me? Some examples or maybe specific tutorials to achieve this would be great.
There is not only one correct way of managing screens. Libido gives you the freedom to do it exactly how you please. You can extend the Screen class to make screens for the different needs of your project. You can manage your screens as states and manage them with a state manager.
Regarding the Pause and Game Over screen, you can do that in different ways too.
You can have a dedicated screen to switch to or you can have a Pause and GameOver state in your Game state/screen and show the Pause/GameOver elements on top of your gamescreen while the game is still in the background.
So there is not a single correct way of doing it. The correct way is what works for your game.
For some inspiration:
pixnbgames.com : How to manage screens
Brent Aureli : Game State Manager
As #IronMonkey has answered, there is no "correct" way.
I do it with one GameScreen class only, and have a lot of different states inside the GameScreen class. The GameScreen class is very simple and short (100-200 LOC), and is responsible for switching between states. States are similar to the GameScreen class, but they can be entered and exited without the need to instantiate new objecs.
class GameScreen extends ScreenAdapter implements Disposable {
GameState menuState;
GameState playState;
GameState currentState;
public GameScreen(final MyGame game) {
menuState = new MenuState(this);
playState = new PlayState(this);
}
public void setState(GameState state) {
if(currentState == state) return;
// states have a method 'exit' where you can pause them or finalize something
if(currentState != null)
currentState.exit();
currentState = state;
// also states have 'enter' where you can unpause or init something when entering
currentState.enter();
}
public void render(float delta) {
currentState.render(delta);
}
}
First, this is very resource efficient, because the needed states are created only once when the game is started. Second, because you never destroy the states, but just change them and call enter/exit, they always retain perfectly their current state, i.e. variables, objects and everything and when you go back to a state, it is exactly as it was before you left it.
GameState is interface and you are free to implement it as you wish.
public interface GameState
{
public void enter();
public void exit();
public void update(float delta);
public void render(SpriteBatch batch, float delta);
public String toString();
public void dispose();
}
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
Hello I am trying to draw "whiteballoon" in main from a serperate class called whiteBalloon. The point is , whenever I call this class's method render() I want to be able to have multiple sprites on screen, clones of each other. The below code is giving me a null exception..
this is the class that i am calling from the main loop.
class whiteBalloon{
Sprite whiteballoon;
SpriteBatch batch;
OrthographicCamera camera;
public whiteBalloon(SpriteBatch batch){
}
public void create(){
batch = new SpriteBatch();
whiteballoon = new Sprite(new Texture("white_balloon.png"));
whiteballoon.setPosition(0, 0);
camera = new OrthographicCamera(Gdx.graphics.getWidth(),
Gdx.graphics.getHeight());
}
public void render(){
System.out.println("hey");
batch.begin();
whiteballoon.draw(batch);
batch.end();
}
}
and then i call it by using
whiteBalloon grumpface;
grumpface = new whiteBalloon();
grumpface.render();
You need to call grumpface.create() before grumpface.render() or just put create() method inside constructor:
public whiteBalloon(){
create();
}
Also your constructor requires a SpriteBatch object as argument, but you don't provide it later in code, so it uses default (empty) constructor instead of the one you created.
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.