Problems loading assets in libgdx - java

I'm new to the world of app development, but I already have some specific knowledge. But my issue is the following involving libgdx and Android Studio:
When trying to load a texture through the Assets Manager method, the following error occurs:
`
E/AndroidRuntime: FATAL EXCEPTION: GLThread 593
Process: br.com.tpgames.dbz, PID: 19495
com.badlogic.gdx.utils.GdxRuntimeException: Asset not loaded: bater_1/goku2.png
at com.badlogic.gdx.assets.AssetManager.get(AssetManager.java:172)
at com.badlogic.gdx.assets.AssetManager.get(AssetManager.java:143)
at br.com.tpgames.dbz.SplashScreen.<init>(SplashScreen.java:53)
`
My codes:
main class:
`
public class MainClass extends Game {
public AssetManager manager;
public void create () {
setScreen(new SplashScreen (this, manager));
}
}
`
Splash screen
`
public class SplashScreen implements Screen {
private Game game;
private AssetManager manager;
private float time = 0;
private SpriteBatch batch;
private Texture tex;
long startime;
public Texture goku;
public SplashScreen(Game game, AssetManager manager){
this.game = game;
this.manager = manager;
batch = new SpriteBatch();
tex = new Texture("logo.png");
startime = TimeUtils.millis();
manager = new AssetManager();
for (int i=1;i<=5;i++){
manager.load("bater_1/"+i+".png",Texture.class);
}
boolean load = manager.isLoaded("bater_1/goku1.png");
Gdx.app.log("Log", String.valueOf(load));
goku = manager.get("bater_1/goku2.png",Texture.class);
}
#Override
public void show() {
}
#Override
public void render(float delta) {
time+=delta;
if (manager.update() && time >=2){ //Se o tempo for maior que 2 segundos, vai abrir a tela principal
game.setScreen(new Tela_Principal(game,manager));
}
Gdx.gl.glClearColor(1,1,1,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(tex, (float) (screenx*0.26), (float) (screeny*0.1), (float) (screenx*0.5), (float) (screeny*0.8));
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() {
}
}
`
Constants
`
public class Constantes {
public static int screenx = Gdx.graphics.getWidth();
public static int screeny = Gdx.graphics.getHeight();
}
`
Main screen
`
public class Tela_Principal implements Screen {
private Game game;
private AssetManager manager;
private SpriteBatch batch;
private SplashScreen splashScreen;
// private Texture goku;
public Tela_Principal(Game game, AssetManager manager){
this.game = game;
this.manager = manager;
splashScreen = new SplashScreen(game,manager);
for (int i=1;i<=5;i++){
manager.load("bater_1/goku"+i+".png",Texture.class);
}
batch = new SpriteBatch();
// goku = manager.get("bater_1/goku1.png",Texture.class);
}
#Override
public void show() {
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0,1,0,0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(splashScreen.goku, (float) (screenx *0.1), (float) (screeny*0.1));
batch.end();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
}
}
`
I thank you for your help!!

manager.load() will queue your asset, not immediately load it.
Only when manager.update() returns true will the assets be available.
Looks like your problem is in SplashScreen
for (int i=1;i<=5;i++){
manager.load("bater_1/"+i+".png",Texture.class);
}
//not allowed
goku = manager.get("bater_1/goku2.png",Texture.class);
AssetManager is well explained here https://libgdx.com/wiki/managing-your-assets

Related

libGDX manager.update() blocking animations

I successfully implemented a gifdecoder in my project and wrote a gifloader for it to use it with the assetmanager. I am able to load the gif in the assetmanager and I am also able to draw it. But everytime I try to load gifs in my assetmanager with manager.update() I can not draw animations anymore, only non animated textures.
Here is my code I hope somebody has an idea
public class Load implements Screen {
private SpriteBatch batch;
private Animation<TextureRegion> loadingAnimation;
private TextureAtlas atlasLoading = new TextureAtlas(Gdx.files.internal("atlas/loadingAnimation.atlas"));
float stateTime;
MainExecute lr;
public FileHandleResolver resolver = new InternalFileHandleResolver();
public AssetManager manager = new AssetManager();
private final Animation animation = GifDecoder.loadGIFAnimation(Animation.PlayMode.NORMAL, Gdx.files.internal("data/loading.gif").read());
public Load(MainExecute lr){
this.lr = lr;
}
public Texture Bg1;
#Override
public void show() {
Bg1 = new Texture(Gdx.files.internal("bggamescreen.png"));
batch = new SpriteBatch();
manager.setLoader(GIF.class,new Gifloader(resolver));
manager.load("data/BackgroundAnim.gif",GIF.class);
stateTime = 0f;
}
#Override
public void render(float delta) {
if (manager.update())
{
lr.setScreen(new MainMenu(lr));
}
stateTime += delta;
// loadingAnimation = new Animation<TextureRegion>(0.5f, atlasLoading.findRegions("loading"),Animation.PlayMode.LOOP);
TextureRegion currentFrame = (TextureRegion) animation.getKeyFrame(stateTime, true);
batch.begin();
batch.draw(Bg1,0,0,Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
batch.draw(currentFrame, 0, 0, 200, 200);
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() {
}
}
Strange code, you are drawing animation before it finish loading. You need to waiting to load your animation, try smth like this.
if (manager.update())
{
loadingAnimation = new Animation<TextureRegion>(0.5f, atlasLoading.findRegions("loading"),Animation.PlayMode.LOOP);
TextureRegion currentFrame = (TextureRegion) animation.getKeyFrame(stateTime, true);
lr.setScreen(new MainMenu(lr));
}

LibGdx: Shaperenderer Rect not being drawn on Screen

Trying to create a simple loading Screen. The below code prints the correct progress, so I know that part works. But the rectangle is not being drawn. Not sure what is wrong.
Full LoadingScreen:
public class LoadingScreen implements Screen {
private static final float PROGRESS_BAR_WIDTH = MyGdxGame.WIDTH / 2f;
private static final float PROGRESS_BAR_HEIGHT = 50f;
GdxAssetManager assetManager;
Stage stage;
//Table mainTable;
private ShapeRenderer shapeRenderer;
private MyGdxGame game;
public LoadingScreen(MyGdxGame game){
this.game = game;
assetManager = game.getAssetManager();
shapeRenderer = new ShapeRenderer();
stage = new Stage(new StretchViewport(MyGdxGame.WIDTH, MyGdxGame.HEIGHT));
}
#Override
public void show() {
assetManager.loadGeneral();
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
renderProgressBar();
if (assetManager.getManager().update()) {
game.setScreen(new LoginScreen(game));
}
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
}
private void renderProgressBar() {
float progress = assetManager.getManager().getProgress();
System.out.println(PROGRESS_BAR_WIDTH * progress);
shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
shapeRenderer.setColor(Color.RED);
shapeRenderer.rect(
(MyGdxGame.WIDTH - PROGRESS_BAR_WIDTH) / 2f,
(MyGdxGame.HEIGHT - PROGRESS_BAR_HEIGHT) / 2f,
PROGRESS_BAR_WIDTH * progress,
PROGRESS_BAR_HEIGHT
);
shapeRenderer.end();
}
#Override
public void resize(int width, int height) {
stage.getViewport().update(width, height);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
dispose();
}
#Override
public void dispose() {
stage.dispose();
shapeRenderer.dispose();
}
}
I guess methods of interest are render and renderProgressBar. Like I said, all I get is a white background until the loading is finished, but the print inside renderProgressBar prints the correct values.
Set projectionMatrix of ShapeRenderer using stage camera.
shapeRenderer.setProjectionMatrix(stage.getCamera().combined);

Trying to create a moving sprite on a scrolling background

I got interested on Android, I'm new at it so I created a scrolling background and I want to put a sprite on it I already created a character class and the scroll background. I want to make the sprite move to the right but I'm getting error on my GamePanel.
The error is Non-static method(android.graphics.Canvas) cannot be referenced from a static context, what does it mean and How am I going to fix this and my make the sprite look like running to the right?
Here's my code:
public class GamePanel extends SurfaceView implements SurfaceHolder.Callback {
public static final int WIDTH = 856;
public static final int HEIGHT = 480;
public static int Score =0;
public static int Highscore;
private MainThread thread;
private Background bg;
private Bitmap bmp;
public GamePanel(Context context) {
super(context);
getHolder().addCallback(this);
thread = new MainThread(getHolder(), this);
setFocusable(true);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
while(retry) {
try {
thread.setRunning(false);
thread.join();
}catch(InterruptedException e) {
e.printStackTrace();
retry = false;
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
bg = new Background(BitmapFactory.decodeResource(getResources(), R.drawable.gamebg));
bmp = BitmapFactory.decodeResource(getResources(), R.drawable.deer);
bg.setVector(-5);
thread.setRunning(true);
thread.start();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return super.onTouchEvent(event);
}
public void update() {
Score += 2;
if (Score > Highscore) {
Highscore = Score;
}
bg.update();
}
#SuppressLint("MissingSuperCall")
#Override
public void draw(Canvas canvas) {
final float scaleFactorX = (float)getWidth()/WIDTH;
final float scaleFactorY = (float)getHeight()/HEIGHT;
if(canvas !=null) {
final int savedState = canvas.save();
canvas.scale(scaleFactorX, scaleFactorY);
bg.draw(canvas);
canvas.restoreToCount(savedState);
Paint textpaint = new Paint();
textpaint.setTextSize(30);
canvas.drawText("Score:" +String.valueOf(Score), 0, 32, textpaint);
canvas.drawText("High Score: "+String.valueOf(Highscore), 0, 64, textpaint);
}
}
#Override
protected void onDraw(Canvas canvas) {
Character.onDraw(canvas);
}
}
You cannot access non static methods from a static context. So if you want to access a function or an object of the GamePanel class, you need to call this member by using the object instance of GamePanel class.
Just an example:
wrong:
GamePanel.draw(canvas);
correct:
GamePanel gamePanel = new GamePanel(this);
gamePanel.draw(canvas);

Can't switch screen [Libgdx]

i'm new to libgdx and i can't figure out what i do wrong.
In my game I just want to switch between 2 screens (first is menuScreen, second is gameScreen). I have created these two screens and one game class, it all looks okay. But when i call my method setScreen(new GameScreen()) nothing happens. Also i should say, that i used screen and game classes in my previous project and all was ok, when i compare my current code to previous one i do not see any differences, so it is very curiously.
Here is my MenuScreen class:
MenuScreen implements Screen {
private SpriteBatch batch ;
private Texture texture;
private float timePassed;
public MenuScreen() {
timePassed = 0;
batch = new SpriteBatch();
texture = new Texture("texture.png");
#Override
public void render (float delta) {
timePassed += Gdx.graphics.getDeltaTime();
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
if (timePassed > 5) {GameClass.getInstance().setScreen(new GameScreen());} //it looks strange, but it's to check if all works properly
batch.begin();
batch.draw(texture, 0, 0);
batch.end();
}
#Override
public void dispose() {
batch.dispose();
texture.dispose();
}
#Override
public void hide() {
}
#Override
public void resume() {
}
#Override
public void pause() {
}
#Override
public void resize(int width, int height) {
}
#Override
public void show() {
}}
Here is my GameScreen class:
GameScreen implements Screen {
private SpriteBatch batch2 ;
private Texture texture2;
public MenuScreen() {
batch2 = new SpriteBatch();
texture2 = new Texture("texture2.png");
}
#Override
public void render (float delta) {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch2.begin();
batch2.draw(texture2, 0, 0);
batch2.end();
}
#Override
public void dispose() {
batch2.dispose();
texture2.dispose();
}
#Override
public void hide() {
}
#Override
public void resume() {
}
#Override
public void pause() {
}
#Override
public void resize(int width, int height) {
}
#Override
public void show() {
}}
And Game class:
public class ClassGame extends Game {
public static ClassGame getInstance(){
ClassGame instance = new ClassGame();
return instance;
}
#Override
public Screen getScreen() {
return super.getScreen();
}
#Override
public void setScreen(Screen screen) {
super.setScreen(screen);
}
#Override
public void resize(int width, int height) {
super.resize(width, height);
}
#Override
public void render() {
super.render();
}
#Override
public void resume() {
super.resume();
}
#Override
public void pause() {
super.pause();
}
#Override
public void dispose() {
super.dispose();
}
public ClassGame() {
super();
}
#Override
public void create() {
MenuScreen menuScreen = new MenuScreen();
setScreen(menuScreen);
}}
This is how I did for the same problem, i had three classes for two screen to switch between them. Here I am switching between second and third using a image actor as button.I also used two constructors in each class, one of them constructors with no arguments, below is my code hope you will get it.
My main class code:
public class First extends Game{
private Game game;
public Main(){ game=this; }
public void create() {
game.setScreen(new Second(game)); }}
Below is my first screen class code
public class Second implements Screen{
private Game second;
public Second(Game second){this.second=second;}
public Second(){}
// your code
Stage myStage=new Stage(new ScreenViewport());
Group myGroup=new Group();
Image secondButton=new Image(new Texture(Gdx.files.internal("image.png")));
public void show(){
myGroup.addActor(secondButton);
secondButton.addListener(new InputListener(){
second.setScreen(new Third(second)); });}
public void render(float delta) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
myStage.act(Gdx.graphics.getDeltaTime());
myStage.draw(); }
public void resize(int width, int height) {}
public void pause(){}
public void resume(){}
public void hide(){}
public void dispose(){}}}
And my next screen class code
public class Third implements Screen{
private Game third;
public Third(Game third){
this.third=third;}
public Third(){}
// your code
Stage myStage=new Stage(new ScreenViewport());
Group myGroup=new Group();
Image thirdButton=new Image(new Texture(Gdx.files.internal("image.png")));
public void show() {
myGroup.addActor(thirdButton);
thirdButton.addListener(new InputListener(){
third.setScreen(new Third(third));});}
public void render(float delta) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
myStage.act(Gdx.graphics.getDeltaTime());
myStage.draw();}
public void resize(int width, int height) { }
public void pause(){}
public void resume(){}
public void hide(){}
public void dispose(){}}}
I got it, guys. In my previous project i declared instance field outside of getInstance(). Like this :
public static GameClass instance = new GameClass();
public static GameClass getInstance(){
return instance;
}
But i still need your help. I don't know how this small thing wasn't letting me switch screens.

How to pause the game in Screen libgdx?

Sorry for my question , but i am stuck. I am new in develop game with lib gdx and don`t judge me strictly.
I have my game activity:
public class MyGame extends Game {
MenuScreen menu;
SplashScreen splash;
DefendScreen def;
#Override
public void create() {
// Gdx.app.log("LogGame", "MyGame create");
menu = new MenuScreen(this);
splash = new SplashScreen(this);
def = new DefendScreen(this);
setScreen(splash);
}
#Override
public void resize(int width, int height) {
}
#Override
public void render() {
super.render();
}
#Override
public void pause() {
super.pause();
}
#Override
public void resume() {
super.resume();
}
#Override
public void dispose() {
}
}
I have two screens :
public class MenuScreen implements Screen, InputProcessor {
public MenuScreen(final MyGame gam) {
game = gam;
cam = new OrthographicCamera();
cam.setToOrtho(false, 800, 480);
w = Gdx.graphics.getWidth();
h = Gdx.graphics.getHeight();
defScreen = new DefendScreen(game);
spriteBatch = new SpriteBatch();
stage = new Stage();
}
#Override
public void dispose() {
Gdx.app.log("LogGame", "splashs dispose");
Gdx.input.setInputProcessor(null);
try {
spriteBatch.dispose();
stage.dispose();
font12.dispose();
} catch (Exception e) {
}
}
#Override
public void hide() {
// TODO Auto-generated method stub
}
#Override
public void pause() {
}
#Override
public void render(float arg0) {
SetCamera(CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2f);
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act(); // update all actors
stage.draw();
}
#Override
public void resize(int arg0, int arg1) {
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void show() {
stage.addActor(new WorldMenu(new Texture(Gdx.files
.internal("images/bg/pause_back.png"))));
Gdx.input.setInputProcessor(stage);
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(
Gdx.files.internal("font/trebuchet_ms.ttf"));
FreeTypeFontParameter parameter = new FreeTypeFontParameter();
parameter.size = 25;
font12 = generator.generateFont(parameter);
generator.dispose();
DrawLeftMeu();
DrawRightMeu();
DrawSetingsMenu();
}}
And game screen where i have pause button:
public class DefendScreen implements Screen, InputProcessor {
public DefendScreen(final MyGame gam) {
game = gam;
cam = new OrthographicCamera();
cam.setToOrtho(false, 800, 480);
startTime = TimeUtils.millis();
spriteBatch = new SpriteBatch();
stage = new Stage();
w = Gdx.graphics.getWidth();
h = Gdx.graphics.getHeight();
}
#Override
public void dispose() {
Gdx.app.log("LogGame", "defend dispose");
try {
combo0.dispose();
combo1.dispose();
combo2.dispose();
good0.dispose();
good1.dispose();
bad0.dispose();
bad1.dispose();
bad2.dispose();
bad3.dispose();
bad4.dispose();
music.dispose();
music.stop();
spriteBatch.dispose();
font.dispose();
pbar.dispose();
scores.dispose();
} catch (Exception e) {
}
}
#Override
public void hide() {
}
#Override
public void pause() {
// this.state = State.PAUSE;
}
#Override
public void render(float delta) {
SetCamera(CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2f);
switch (state) {
case RUN:
RunGame();
break;
case PAUSE:
// do stuff here
break;
case RESUME:
break;
default:
break;
}
}
#Override
public void resize(int arg0, int arg1) {
}
#Override
public void resume() {
this.state = State.RESUME;
}
#Override
public void show() {
regions = new ArrayList<Integer>();
addRegions();
initSounds();
speedgame = speedgameEasy;
stage.addActor(worldActor);
stage.addActor(pauseActor);
startTime = TimeUtils.millis();
stage.addListener(clickList);
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(
Gdx.files.internal("font/trebuchet_ms.ttf"));
FreeTypeFontParameter parameter = new FreeTypeFontParameter();
parameter.size = 25;
font = generator.generateFont(parameter);
generator.dispose();
pbar = new Texture(Gdx.files.internal("images/bg/line_indicator.png"));
scores = new Texture(
Gdx.files.internal("images/game_images/scorebox.png"));
Gdx.input.setInputProcessor(stage);
Gdx.input.setCatchBackKey(true);
}}
And my main questions !!!
--> what i must do that on pause action i can freeze the game action and call menu screen (whish have button resume)?
--> what i mus do in resume onclick to show game action resume?
on stackoverflow an other forums i find some explains about my question, which means to implement in resume some switch case with choices of game state, but i am do not understand how its realize in my code.
Thanks everyone.
In your game screen you should have a button (an actor added to the stage) which implements a ClickListener that calls either pause() or resume() depending on the current state of the game.
It should look something like this:
pauseButton.addListener(new ClickListener() {
public void clicked(InputEvent evt, float x, float y) {
if (!paused) Gdx.app.getApplicationListener().pause();
else Gdx.app.getApplicationListener().resume();
}
});
Where paused is a boolean variable in your game screen class.
In my opinion this is the easiest way to do this.

Categories