How to show loading screen class before preferences [Libgdx & android] - java

So I am programming a game, and implemented preferences to save/load some simple data for sound/high score, nothing too much. The problem is that when I load preferences for the first time on a physical phone (samsung g. s3) it takes about 15sec and on s5 it takes about 5-8secs and in that time it shows black screen even though I have set the loading screen to be shown first, before preferences are used.
In my main application code I set screen to loadingScreen
loadingScreen = new com.package.game.Screens.LoadingScreen(this);
mainScreen = new com.package.game.Screens.MainScreen(this);
gameScreen = new com.package.game.Screens.GameScreen(this);
settingsScreen = new com.package.game.Screens.SettingsScreen(this);
this.setScreen(loadingScreen);
and then in my loading screen I access preferences:
#Override
public void show() {
this.progress_assets = 0f;
this.progress_assets = 0f;
font_loading = app.initFont(50, 1, 255, 255, 255, 1);
queueAssets();
loading_db();
}
private void loading_db() {
if(database.get_first_time()){
//do some introduction for first time run
Gdx.app.log("db","first time worked");
database.set_first_time();
progress_db=1f;
}else{
Gdx.app.log("db","first time is set false");
progress_db=1f;
}
}
and my preferences class:
package com.package.game.Engine;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Preferences;
import com.package.game.Application;
public class Database {
private Preferences preferences;
//database
private Preferences pref_settings;
private Preferences pref_score;
private Preferences pref_unlocks;
public Database(){
pref_settings = Gdx.app.getPreferences("com.package.game.settings");
pref_score = Gdx.app.getPreferences("com.package.game.score");
pref_unlocks = Gdx.app.getPreferences("com.package.game.unlocks");
}
//checking if first time run
public boolean get_first_time(){
return pref_settings.getBoolean("First_run",true);
}
public void set_first_time(){
pref_settings.putBoolean("First_run",false);
for(int i=0;i<7;i++){
pref_unlocks.putBoolean("unlock_"+i,true);
}
pref_unlocks.flush();
pref_settings.flush();
}
//settings
public boolean getSound(){
return pref_settings.getBoolean("sound_on",true);
}
public void setSound(boolean sound){
pref_settings.putBoolean("sound_on",sound);
pref_settings.flush();
}
//High Score Mode:
//Classic
public int getScore_classic(int place){
return pref_score.getInteger("score_classic_"+place,0);//default value 0 so we could place new score if we havent reached it
}
public void setScore_classic(int place,int scored){
pref_score.putInteger("score_classic_"+place,scored);
pref_score.flush();
}
//Recipe
public int getScoreRec(int place){
return pref_score.getInteger("score_recipe_"+place,0);//default value 0 so we could place new score if we havent reached it
}
public void setScoreRec(int place,int scored){
pref_score.putInteger("score_recipe_"+place,scored);
pref_score.flush();
}
//food unlocks
public boolean getFoodUnlock(int unlockID){
return pref_unlocks.getBoolean("unlock_"+unlockID,false);
}
public void setFoodUnlock(int unlockID,boolean state){
pref_unlocks.putBoolean("unlock_"+unlockID,state);
pref_unlocks.flush();
}
}
I'm not sure if creating 3 pref. files is good, but i would like to know how to show screen before pref. file being created/loaded.
Edit: Adding my main code
package com.mindutis.game;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;
import com.badlogic.gdx.utils.viewport.ExtendViewport;
import com.mindutis.game.Screens.LoadingScreen;
public class Application extends Game {
public static int V_WIDTH ;
public static int V_HEIGHT;
public OrthographicCamera camera;
public SpriteBatch batch;
public AssetManager assets;
public com.mindutis.game.Screens.LoadingScreen loadingScreen;
public com.mindutis.game.Screens.SplashScreen splashScreen;
public com.mindutis.game.Screens.MainScreen mainScreen;
public com.mindutis.game.Screens.GameScreen gameScreen;
public com.mindutis.game.Screens.SettingsScreen settingsScreen;
public BitmapFont f_game_name;
public String t_game_name;
public String[] font_type = new String[2];
private boolean firstFrame = true;
private boolean loading = true;
#Override
public void create() {
assets = new AssetManager();
camera = new OrthographicCamera();
V_WIDTH= Gdx.graphics.getWidth();
V_HEIGHT = Gdx.graphics.getHeight();
camera.setToOrtho(false, V_WIDTH, V_HEIGHT);
batch = new SpriteBatch();
//Global var.
//font initializer
font_type[0] = "fonts/comics_bold.ttf";
font_type[1] = "fonts/vdj.ttf";
//game name
t_game_name = " Catch a\nSandwich";
f_game_name = initFont(70, 0, 255, 255, 255, 1);
loadingScreen = new com.mindutis.game.Screens.LoadingScreen(this);
splashScreen = new com.mindutis.game.Screens.SplashScreen(this);
mainScreen = new com.mindutis.game.Screens.MainScreen(this);
gameScreen = new com.mindutis.game.Screens.GameScreen(this);
settingsScreen = new com.mindutis.game.Screens.SettingsScreen(this);
// this.setScreen(loadingScreen);
}
//int size=font size, int x = font type
public BitmapFont initFont(int size, int type, float red, float green, float blue, float alpha) {
BitmapFont font;
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal(font_type[type]));
FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
parameter.size = size;
font = generator.generateFont(parameter);
font.setColor(red / 255f, green / 255f, blue / 255f, alpha);
return font;
}
#Override
public void render() {
if (firstFrame){
Gdx.gl.glClearColor(.2f, .67f, .88f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
f_game_name.draw(batch, t_game_name, camera.viewportWidth / 2 - 150, camera.viewportHeight - 100);
batch.end();
firstFrame = false;
} else {
if(loading){
loading=false;
loadEverything();
}
// Notice you don't actually render anything so what you previously drew stays on the screen.
}
super.render();
}
private void loadEverything(){
// load your font, assets, prefs, etc.
this.setScreen(loadingScreen);
// setScreen(loadingScreen);
}
#Override
public void dispose() {
batch.dispose();
assets.dispose();
f_game_name.dispose();
loadingScreen.dispose();
splashScreen.dispose();
mainScreen.dispose();
gameScreen.dispose();
settingsScreen.dispose();
}
}
Loading screen class:
package com.mindutis.game.Screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.mindutis.game.Application;
import com.mindutis.game.Engine.Database;
public class LoadingScreen implements Screen {
private final Application app;
private Database database;
private BitmapFont font_loading;
private boolean load;
private ShapeRenderer shapeRenderer;
private Stage stage;
private String t_loading;
private float progress_assets,progress_db;
private boolean firstFrame = true;
private boolean loading = true;
public LoadingScreen(Application app) {
this.app = app;
database = new Database();
this.stage = new Stage(new FitViewport(com.mindutis.game.Application.V_WIDTH, com.mindutis.game.Application.V_HEIGHT, app.camera));
this.shapeRenderer = new ShapeRenderer();
t_loading = "Loading...";
load=false;
}
private void queueAssets() {
//good food
//bread
app.assets.load("img/Food/breadtop.png", Texture.class);
app.assets.load("img/Food/breadbot.png", Texture.class);
//rest of the food
app.assets.load("img/Food/food_sheet.png", Texture.class);
//misc
app.assets.load("img/Misc/coin.png", Texture.class);
app.assets.load("img/Misc/soon.png", Texture.class);
app.assets.load("img/Misc/shoptriangle.png", Texture.class);
//buttons
app.assets.load("img/Buttons/button.png", Texture.class);
app.assets.load("img/Buttons/soundBT.png", Texture.class);
app.assets.load("img/Buttons/btX.png", Texture.class);
app.assets.load("img/Buttons/btShop1.png", Texture.class);
//human
app.assets.load("img/Human/human.png", Texture.class);
app.assets.load("img/Human/human1.png", Texture.class);
app.assets.load("img/Human/human2.png", Texture.class);
}
#Override
public void show() {
this.progress_assets = 0f;
this.progress_assets = 0f;
font_loading = app.initFont(50, 1, 255, 255, 255, 1);
queueAssets();
loading_db();
}
private void loading_db() {
if(database.get_first_time()){
//do some introduction for first time run
Gdx.app.log("db","first time worked");
database.set_first_time();
progress_db=1f;
}else{
Gdx.app.log("db","first time is set false");
progress_db=1f;
}
}
#Override
public void render(float delta) {
if (firstFrame){
Gdx.gl.glClearColor(.2f, .67f, .88f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
app.batch.begin();
app.f_game_name.draw(app.batch, app.t_game_name, app.camera.viewportWidth / 2 - 150, app.camera.viewportHeight - 100);
app.batch.end();
firstFrame = false;
} else {
if(loading){
loading=false;}
//input
Gdx.input.setCatchBackKey(true);
Gdx.input.setInputProcessor(new InputAdapter() {
#Override
public boolean keyDown(int keycode) {
if (keycode == Input.Keys.BACK) {
// Do nothing
}
return false;
}
});
Gdx.gl.glClearColor(.2f, .67f, .88f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
update(delta);
app.batch.begin();
font_loading.draw(app.batch, t_loading, app.camera.viewportWidth / 2 - 150, 123);
app.f_game_name.draw(app.batch, app.t_game_name, app.camera.viewportWidth / 2 - 150, app.camera.viewportHeight - 100);
app.batch.end();
shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
shapeRenderer.setColor(Color.WHITE);
shapeRenderer.rect(32, 50, app.camera.viewportWidth - 64, 16);
shapeRenderer.setColor(Color.GREEN);
shapeRenderer.rect(32, 50, (progress_assets+progress_db)/2 * (app.camera.viewportWidth - 64), 16);
shapeRenderer.end();
}
// Notice you don't actually render anything so what you previously drew stays on the screen.
}
private void update(float delta) {
progress_assets = MathUtils.lerp(progress_assets, app.assets.getProgress(), .1f);
if (app.assets.update() && (progress_assets+progress_db)/2 >= app.assets.getProgress() - .01f) {
app.setScreen(app.mainScreen);
}
}
#Override
public void resize(int width, int height) {
stage.getViewport().update(width, height, false);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
shapeRenderer.dispose();
font_loading.dispose();
stage.dispose();
}
}

You can quickly load a single texture to show while everything else loads. Load and show the texture the first time render() is called. Then the second time render() is called, load your stuff, dispose the texture, and switch screens.
public class LoadingScreen extends Screen {
private boolean firstFrame = true;
private Texture texture;
private ExtendViewport viewport;
private MyGame game;
private SpriteBatch batch;
private static final float LOAD_IMAGE_WIDTH = 480, LOAD_IMAGE_HEIGHT = 600;
// Use whatever the loading image dimensions are.
public LoadingScreen (MyGame game, SpriteBatch batch){
this.game = game;
this.batch = batch;
viewport = new ExtendViewport(LOAD_IMAGE_WIDTH, LOAD_IMAGE_HEIGHT);
}
public void resize (int width, int height) {
viewport.update(width, height, false);
viewport.getCamera().position.set(LOAD_IMAGE_WIDTH / 2, LOAD_IMAGE_HEIGHT / 2, 0);
viewport.getCamera().update();
}
public void show (){} // do nothing
public void render (float delta) {
if (firstFrame){
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
viewport.apply();
batch.setProjectionMatrix(viewport.getCamera().combined);
batch.setBlendingDisabled(true);
batch.begin();
batch.draw(texture, 0, 0, LOAD_IMAGE_WIDTH, LOAD_IMAGE_HEIGHT);
batch.end();
firstFrame = false;
} else {
loadEverything();
// Notice you don't actually render anything so what you previously drew stays on the screen.
}
}
private void loadEverything(){
// load your font, assets, prefs, etc.
texture.dispose();
main.setGameScreen();
}
}

Related

How to make .tmx map fill the whole screen

I'm loading a .tmx map using Libgdx and the map is not filling the whole screen. I cannot figure out the problem so as a last resort I'm asking a question here.I'm following a tutorial on YouTube and he did not cover this problem and as a result I cannot continue. I have tried multiple things with no sucess. The map is width: 240 tiles, height: 13 tiles, and tiles are 16 by 16
,
.
This is the code. I think the problem has to do with
renderer = new OrthogonalTiledMapRenderer(map, 1/DBZ.PPM),
gameCam.position.set(gamePort.getWorldWidth()/2,
gamePort.getWorldHeight()/2, 0);,
gameCam = new OrthographicCamera();
gamePort = new FitViewport(DBZ.V_WIDTH/DBZ.PPM, DBZ.V_HEIGHT/DBZ.PPM, gameCam);
public class PlayScreen implements Screen {
private DBZ game;
private OrthographicCamera gameCam;
private Viewport gamePort;
private Hud hud;
private TmxMapLoader maploader;
private TiledMap map;
private OrthogonalTiledMapRenderer renderer;
private World world;
private Box2DDebugRenderer b2dr;
private Goku player;
private TextureAtlas atlas;
public PlayScreen(DBZ game){
atlas = new TextureAtlas("goku.pack");
this.game= game;
gameCam = new OrthographicCamera();
gamePort = new FitViewport(DBZ.V_WIDTH/DBZ.PPM, DBZ.V_HEIGHT/DBZ.PPM, gameCam);
hud = new Hud(game.batch);
maploader= new TmxMapLoader();
map = maploader.load("level1.tmx");
renderer = new OrthogonalTiledMapRenderer(map, 1/DBZ.PPM);
gameCam.position.set(gamePort.getWorldWidth()/2, gamePort.getWorldHeight()/2, 0);
world = new World(new Vector2(0,-10),true);
b2dr = new Box2DDebugRenderer();
new B2WorldCreator(world,map);
player = new Goku(world, this);
}
public TextureAtlas getAtlas(){
return atlas;
}
#Override
public void show() {
}
public void handleInput(float dt){
if (Gdx.input.isKeyJustPressed(Input.Keys.UP))
player.b2body.applyLinearImpulse(new Vector2(0, 4f), player.b2body.getWorldCenter(), true);
if (Gdx.input.isKeyPressed(Input.Keys.RIGHT) && player.b2body.getLinearVelocity().x <= 2)
player.b2body.applyLinearImpulse(new Vector2(0.1f, 0), player.b2body.getWorldCenter(), true);
if (Gdx.input.isKeyPressed(Input.Keys.LEFT) && player.b2body.getLinearVelocity().x >= -2)
player.b2body.applyLinearImpulse(new Vector2(-0.1f, 0), player.b2body.getWorldCenter(), true);
}
public void update(float dt){
handleInput(dt);
world.step(1/60f, 6, 2);
player.update(dt);
gameCam.position.x = player.b2body.getPosition().x;
gameCam.update();
renderer.setView(gameCam);
}
#Override
public void render(float delta) {
update(delta);
Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
renderer.render();
b2dr.render(world, gameCam.combined);
game.batch.setProjectionMatrix(gameCam.combined);
game.batch.begin();
player.draw(game.batch);
game.batch.end();
game.batch.setProjectionMatrix(hud.stage.getCamera().combined);
hud.stage.draw();
}
#Override
public void resize(int width, int height) {
gamePort.update(width, height);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
map.dispose();
renderer.dispose();
world.dispose();
b2dr.dispose();
hud.dispose();
}
}
public class DBZ extends Game{
public SpriteBatch batch;
public static final int V_WIDTH = 400;
public static final int V_HEIGHT = 208;
public static final float PPM = 100;
#Override
public void create () {
batch = new SpriteBatch();
setScreen(new PlayScreen(this));
}
#Override
public void render () {
super.render();
}
#Override
public void dispose () {
batch.dispose();
}
}
public class Goku extends Sprite {
public World world;
public Body b2body;
private TextureRegion gokuStand;
public Goku(World world, PlayScreen screen){
super(screen.getAtlas().findRegion("goku_sprite"));
this.world = world;
defineGoku();
gokuStand = new TextureRegion(getTexture(), 5,12,59,85);
setBounds(0,0,59/DBZ.PPM,85/DBZ.PPM);
setRegion(gokuStand);
}
public void defineGoku(){
BodyDef bdef = new BodyDef();
bdef.position.set(32/DBZ.PPM,32/DBZ.PPM);
bdef.type = BodyDef.BodyType.DynamicBody;
b2body = world.createBody(bdef);
FixtureDef fdef = new FixtureDef();
PolygonShape shape = new PolygonShape();
shape.setAsBox(59/2/DBZ.PPM, 85/2/DBZ.PPM);
fdef.shape = shape;
b2body.createFixture(fdef);
}
public void update(float dt){
setPosition(b2body.getPosition().x - getWidth()/2, b2body.getPosition().y - getHeight()/2 );
}
}
Problem is in placement of camera, attach camera with player so that viewport of camera cover whole screen. I am trying to fix this.
public float gokuStartingPositionX;
public PlayScreen(DBZ game){
.....
new B2WorldCreator(world,map);
gokuStartingPositionX=64/DBZ.PPM; //added in your method
player = new Goku(world, this);
}
public void update(float dt){
handleInput(dt);
world.step(1/60f, 6, 2);
player.update(dt);
//camera position is decided by player position and keep camera in this way so it cover whole viewport width with screen
gameCam.position.x = player.b2body.getPosition().x + gamePort.getWorldWidth()/2 - gokuStartingPositionX;
gameCam.update();
renderer.setView(gameCam);
}
Small modification in Goku
public Goku(World world, PlayScreen screen){
super(screen.getAtlas().findRegion("goku_sprite"));
this.world = world;
defineGoku(screen.gokuStartingPositionX);
gokuStand = new TextureRegion(getTexture(), 5,12,59,85);
setBounds(0,0,59/DBZ.PPM,85/DBZ.PPM);
setRegion(gokuStand);
}
public void defineGoku(float startX){
BodyDef bdef = new BodyDef();
bdef.position.set(startX,32/DBZ.PPM);
bdef.type = BodyDef.BodyType.DynamicBody;
b2body = world.createBody(bdef);
...
}
I believe what you are looking for is the ability to clamp the camera to the map.
This can be achieved using MathUtils.clamp.
gameCam.position.x = MathUtils.clamp(gameCam.position.x, viewportWidth/2 , 38 - viewportWidth/2);
gameCam.position.y = MathUtils.clamp(gameCam.position.y, viewportHeight/2, 208 - viewportHeight/2);
EDIT: Your updated PlayScreen:
package com.edwin.game.Screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.edwin.game.DBZ;
import com.edwin.game.Scenes.Hud;
import com.edwin.game.Sprites.Goku;
import com.edwin.game.Tools.B2WorldCreator;
/**
* Created by Edwin on 3/20/2017.
*/
public class PlayScreen implements Screen {
private DBZ game;
private OrthographicCamera gameCam;
private Viewport gamePort;
private Hud hud;
private TmxMapLoader maploader;
private TiledMap map;
private OrthogonalTiledMapRenderer renderer;
private World world;
private Box2DDebugRenderer b2dr;
private Goku player;
private TextureAtlas atlas;
private float viewportWidth;
private float viewportHeight;
public PlayScreen(DBZ game){
atlas = new TextureAtlas("goku.pack");
this.game= game;
gameCam = new OrthographicCamera();
gamePort = new FitViewport(DBZ.V_WIDTH/DBZ.PPM, DBZ.V_HEIGHT/DBZ.PPM, gameCam);
hud = new Hud(game.batch);
maploader= new TmxMapLoader();
map = maploader.load("level1.tmx");
renderer = new OrthogonalTiledMapRenderer(map, 1/DBZ.PPM);
viewportWidth = gamePort.getWorldWidth();
viewportHeight= gamePort.getWorldHeight();
world = new World(new Vector2(0,-10),true);
b2dr = new Box2DDebugRenderer();
new B2WorldCreator(world,map);
player = new Goku(world, this);
}
public TextureAtlas getAtlas(){
return atlas;
}
#Override
public void show() {
}
public void handleInput(float dt){
if (Gdx.input.isKeyJustPressed(Input.Keys.UP))
player.b2body.applyLinearImpulse(new Vector2(0, 4f), player.b2body.getWorldCenter(), true);
if (Gdx.input.isKeyPressed(Input.Keys.RIGHT) && player.b2body.getLinearVelocity().x <= 2)
player.b2body.applyLinearImpulse(new Vector2(0.5f, 0), player.b2body.getWorldCenter(), true);
if (Gdx.input.isKeyPressed(Input.Keys.LEFT) && player.b2body.getLinearVelocity().x >= -2)
player.b2body.applyLinearImpulse(new Vector2(-0.1f, 0), player.b2body.getWorldCenter(), true);
}
public void update(float dt){
handleInput(dt);
world.step(1/60f, 6, 2);
player.update(dt);
gameCam.position.x = player.b2body.getPosition().x;
// cam pos / var to clamp / min val / max val
gameCam.position.x = MathUtils.clamp(gameCam.position.x, viewportWidth/2 , 38 - viewportWidth/2);
gameCam.position.y = MathUtils.clamp(gameCam.position.y, viewportHeight/2, 208 - viewportHeight/2);
System.out.println(gameCam.position.x);
gameCam.update();
renderer.setView(gameCam);
}
#Override
public void render(float delta) {
update(delta);
Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
renderer.render();
//
//
b2dr.render(world, gameCam.combined);
game.batch.setProjectionMatrix(gameCam.combined);
game.batch.begin();
player.draw(game.batch);
game.batch.end();
game.batch.setProjectionMatrix(hud.stage.getCamera().combined);
hud.stage.draw();
}
#Override
public void resize(int width, int height) {
gamePort.update(width, height);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
map.dispose();
renderer.dispose();
world.dispose();
b2dr.dispose();
hud.dispose();
}
}

Libgdx viewport not stretching

I'm currently having a problem creating a stretchedViewPort in libgdx.
As you can see in the image I added the gamescreen is not stretched over the whole screen and there are black spaces. I'm wondering what I'm doing wrong.
I provided the relevant parts of the code below.
Furthermore I also tried to use asign the viewport in to the stage in the oncreate function like this: m_stage = new Stage(m_viewport); But in that case I got a black screen and nothing was rendered (tough there were no compile errors).
Can someone point out what I'm doing wrong or what I'm missing.
Thanks in advance!
Kind regards,
Cavasta
package com.block.it;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.viewport.StretchViewport;
public class GameMenu implements Screen {
private BlockIt m_blockIt;
private Texture m_btexture = new Texture(Gdx.files.internal("mainmenu1.png"));
private Image m_background = new Image(m_btexture);
private Texture m_starttexture = new Texture(Gdx.files.internal("buttons/c_start.png"));
private Image m_startGame = new Image(m_starttexture);
private Texture m_optionstexture = new Texture(Gdx.files.internal("buttons/c_controls.png"));
private Image m_options = new Image(m_optionstexture);
private Texture m_highscoretexture = new Texture(Gdx.files.internal("buttons/c_highscores.png"));
private Image m_highscore = new Image(m_highscoretexture);
private Texture m_continueTexture = new Texture(Gdx.files.internal("buttons/c_resume_game.png"));
private Image m_continue = new Image(m_continueTexture);
private Texture m_playerIcon = new Texture(Gdx.files.internal("player/player_move_front.png"));
private Image m_player = new Image(m_playerIcon);
private int m_buttonPressed = -1;
private boolean m_gameInProgress = false;
private StretchViewport m_viewport;
private PerspectiveCamera m_camera;
private Stage m_stage = new Stage();
public GameMenu(BlockIt blockIt, boolean gameInProgress) {
m_blockIt = blockIt;
m_camera = new PerspectiveCamera();
m_viewport = new StretchViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), m_camera);
m_viewport.update(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true);
m_stage = new Stage();
}
#Override
public void show() {
if (!m_gameInProgress) {
m_startGame.setX(227);
m_startGame.setY(270);
m_startGame.addListener(new ClickListener() {
#Override
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
// m_blockIt.startNewGame();
}
#Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
// switch to a new texture
/*Texture newTexture = new Texture(Gdx.files.internal("buttons/c_new_game.png"));
m_startGame.setDrawable(new SpriteDrawable(new Sprite(newTexture)));
*/
m_player.setX(-64);
m_player.setY(300);
m_stage.addActor(m_player);
m_buttonPressed = 0;
return true;
}
});
} else {
m_continue.setX(227);
m_continue.setY(270);
m_continue.addListener(new ClickListener() {
#Override
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
}
});
}
m_stage.addActor(m_background); //adds the image as an actor to the stage
if (m_gameInProgress) {
m_stage.addActor(m_continue);
} else {
m_stage.addActor(m_startGame);
}
Gdx.input.setInputProcessor(m_stage);
}
#Override
public void render(float delta) {
m_camera.update();
Gdx.gl.glClearColor(0, 0, 0, 1); //sets clear color to black
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); //clear the batch
m_stage.act(); //update all actors
m_stage.draw(); //draw all actors on the Stage.getBatch()
}
#Override
public void resize(int width, int height
) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
}
}
You have to set the camera and viewport to the value u used to program the world:
eg. If your world is 800*480:
camera = new OrthographicCamera(800,480);
fitViewport = new FitViewport(800, 480, camera);
You have to update the viewport when the window is resized:
#Override
public void resize(int width, int height) {
m_viewport.update(width, height, true);
}

LibGDX basic stage draw error

I'm trying to create a game, but my code keeps giving me error:
Exception in thread "LWJGL Application" java.lang.IllegalArgumentException: no uniform with name 'u_projModelView' in shader
at com.badlogic.gdx.graphics.glutils.ShaderProgram.fetchUniformLocation(ShaderProgram.java:287)
at com.badlogic.gdx.graphics.glutils.ShaderProgram.fetchUniformLocation(ShaderProgram.java:277)
at com.badlogic.gdx.graphics.glutils.ShaderProgram.setUniformMatrix(ShaderProgram.java:507)
at com.badlogic.gdx.graphics.glutils.ShaderProgram.setUniformMatrix(ShaderProgram.java:498)
at com.badlogic.gdx.graphics.glutils.ImmediateModeRenderer20.flush(ImmediateModeRenderer20.java:147)
at com.badlogic.gdx.graphics.glutils.ImmediateModeRenderer20.end(ImmediateModeRenderer20.java:160)
at com.badlogic.gdx.graphics.glutils.ShapeRenderer.end(ShapeRenderer.java:1104)
at com.badlogic.gdx.graphics.glutils.ShapeRenderer.check(ShapeRenderer.java:1092)
at com.badlogic.gdx.graphics.glutils.ShapeRenderer.rect(ShapeRenderer.java:389)
at com.badlogic.gdx.scenes.scene2d.ui.Table.drawDebugRects(Table.java:1224)
at com.badlogic.gdx.scenes.scene2d.ui.Table.drawDebug(Table.java:1204)
at com.badlogic.gdx.scenes.scene2d.Group.drawDebugChildren(Group.java:156)
at com.badlogic.gdx.scenes.scene2d.Group.drawDebug(Group.java:139)
at com.badlogic.gdx.scenes.scene2d.Stage.drawDebug(Stage.java:169)
at com.badlogic.gdx.scenes.scene2d.Stage.draw(Stage.java:132)
at net.lukshe.lukshegame2.screens.MainMenu.render(MainMenu.java:71)
at com.badlogic.gdx.Game.render(Game.java:46)
at net.lukshe.lukshegame2.LuksheGame.render(LuksheGame.java:23)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:215)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)
MainMenu.java:
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL30;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle;
public class MainMenu implements Screen {
private Stage stage; //done
private TextureAtlas atlas; //done
private Skin skin; //done
private Table table; //done
private TextButton buttonplay, buttonexit;
private BitmapFont white; //done
private Label heading;
#Override
public void show() {
stage = new Stage();
atlas = new TextureAtlas("ui/button.pack");
skin = new Skin(atlas);
table = new Table(skin);
table.setBounds(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
white = new BitmapFont(Gdx.files.internal("font/white.fnt"), false);
//Set the button style
TextButtonStyle textButtonStyle = new TextButtonStyle();
textButtonStyle.up = skin.getDrawable("buttonup");
textButtonStyle.down = skin.getDrawable("buttondown");
textButtonStyle.pressedOffsetX = 1;
textButtonStyle.pressedOffsetY = -1;
textButtonStyle.font = white;
textButtonStyle.fontColor = Color.BLACK;
//Creating exit button
buttonexit = new TextButton("Exit", textButtonStyle);
buttonexit.pad(20);
//Add button to the table
table.add(buttonexit);
//Debug
table.debug();
//Add table to the stage
stage.addActor(table);
}
#Override
public void render(float delta) {
//OpenGL settings
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);
//Render at the speed of delta
stage.act(delta);
//Draw stage
stage.draw();
}
LuksheGame.java:
public class LuksheGame extends Game {
public static final String NAME = "Lukse game (LibGDX)", VERSION = "Pre-Alpha 0.0.0.2";
#Override
public void create() {
setScreen(new Splash());
}
#Override
public void dispose() {
super.dispose();
}
#Override
public void render() {
super.render();
}
#Override
public void resize(int width, int height) {
super.resize(width, height);
}
#Override
public void pause() {
super.pause();
}
#Override
public void resume() {
super.resume();
}
}
If someone can help me, please help.
EDIT:
MainMenu.java is called from Splash.java. In Splash class I'm using Tween engine to increase and decrease opacity of the splash screen.
Splash.java:
public class Splash implements Screen {
private SpriteBatch batch;
private Sprite splash;
private TweenManager twm;
#Override
public void show() {
batch = new SpriteBatch();
twm = new TweenManager();
Tween.registerAccessor(Sprite.class, new SpriteAccessor());
Texture splashtexture = new Texture(Gdx.files.internal("images/splash.png"));
splash = new Sprite(splashtexture);
splash.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Tween.set(splash, SpriteAccessor.alpha).target(0).start(twm);
Tween.to(splash, SpriteAccessor.alpha, 2).target(1).repeatYoyo(1, 2).setCallback(new TweenCallback() {
#Override
public void onEvent(int type, BaseTween<?> source) {
((Game) Gdx.app.getApplicationListener()).setScreen(new MainMenu());
}
}).start(twm);
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);
twm.update(delta);
batch.begin();
splash.draw(batch);
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() {
batch.dispose();
splash.getTexture().dispose();
}
}

Libgdx NullPointerException when trying to update viewport

I'm trying to update the game's viewport when the game resizes, but when I start the game, I get a java.lang.NullPointerException:
Exception in thread "LWJGL Application" java.lang.NullPointerException
at com.badlogic.gdx.utils.viewport.Viewport.apply(Viewport.java:49)
at com.badlogic.gdx.utils.viewport.ExtendViewport.update(ExtendViewport.java:90)
at com.badlogic.gdx.utils.viewport.Viewport.update(Viewport.java:57)
at me.chrisjosten.testgame.screens.MainScreen.resize(MainScreen.java:82)
at com.badlogic.gdx.Game.setScreen(Game.java:62)
at me.chrisjosten.testgame.create(MainScreen.java:13)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:136)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:114)
In the class, that implements Screen, I have in the resize method, the place where the exception occurs, the following code:
#Override
public void resize(int w, int h) {
viewport.update(w, h);
}
where the viewport is an ExtendViewport created in the constructor of the class. I've tried putting that in the show method to, but then I get the same result.
The full code of the class:
package me.chrisjosten.testgame.screens;
import me.chrisjosten.testgame.MyGame;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.viewport.ExtendViewport;
import com.badlogic.gdx.utils.viewport.FillViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
public class MainScreen implements Screen{
private MyGame game;
private BitmapFont font;
private SpriteBatch batch;
private OrthographicCamera camera;
private Viewport viewport;
private boolean goingUp = false;
private float alpha = 1;
private int gameWidth = 100;
private int gameHeight = 100;
private int screenWidth;
private int screenHeight;
public MainScreen(MyGame g) {
game = g;
System.out.println("screen created");
}
#Override
public void show() {
System.out.println("show");
font = new BitmapFont(Gdx.files.internal("fonts/monospace.fnt"));
font.setColor(1, 1, 1, 1);
batch = new SpriteBatch();
camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
camera.translate(gameWidth / 2, gameHeight / 2);
viewport = new ExtendViewport(gameWidth, gameHeight, camera);
}
#Override
public void render(float delta) {
camera.update();
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
if (goingUp) {
font.setColor(1, 1, 1, alpha);
alpha += 0.025;
} else {
font.setColor(1, 1, 1, alpha);
alpha -= 0.025;
}
if (alpha <= 0) {
goingUp = true;
alpha = 0;
} else if (alpha >= 1) {
goingUp = false;
alpha = 1;
}
batch.setProjectionMatrix(camera.combined);
batch.begin();
String press = "Press start";
font.draw(batch, press, gameWidth / 2 - font.getBounds(press).width / 2, 1);
batch.end();
}
#Override
public void resize(int w, int h) {
viewport.update(w, h);
}
#Override
public void pause() {
// TODO Auto-generated method stub
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void hide() {
// TODO Auto-generated method stub
}
#Override
public void dispose() {
// TODO Auto-generated method stub
font.dispose();
}
}
Does anyone know what I have done wrong?
By moving the code from the show method to the constructor, it works.

Sprite flicker while moving libgdx

This code makes image Border flicker(Flash) while moving left,right,down or up. Why image border flash wile moving even if I use Screen class render() method delta value.
package com.me.mygdxgame;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector3;
public class MoveSpriteExample extends GdxTest implements InputProcessor {
Texture texture;
SpriteBatch batch;
OrthographicCamera camera;
Vector3 spritePosition = new Vector3();
Sprite sprite;
public void resize (int width, int height) {
}
public void create() {
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
batch = new SpriteBatch();
camera= new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
camera.setToOrtho(false, w, h);
texture = new Texture(Gdx.files.internal("data/grasswall.png"));
texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
sprite = new Sprite(texture);
sprite.setSize(32, 32);
spritePosition.y=100;
sprite.setPosition(spritePosition.x,spritePosition.x);
lastUpdateTime = System.nanoTime();
}
public void Update(float Delta)
{
if (Gdx.input.isKeyPressed(Keys.D)==true)
{
spritePosition.x += 150*(Delta / 1000000000.0);
}else if (Gdx.input.isKeyPressed( Keys.A)==true)
{
spritePosition.x -= 150*(Delta / 1000000000.0);
}
else if (Gdx.input.isKeyPressed( Keys.Z)==true)
{
spritePosition.y -= 150*(Delta / 1000000000.0);
}
else if (Gdx.input.isKeyPressed( Keys.W)==true)
{
spritePosition.y += 150*(Delta / 1000000000.0);
}
}
float lastUpdateTime;
float currentTime;
public void render() {
currentTime = System.nanoTime();
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
camera.update();
Update(currentTime - lastUpdateTime);
sprite.setPosition(spritePosition.x,spritePosition.y);
batch.setProjectionMatrix(camera.combined);
batch.begin();
sprite.draw(batch);
batch.end();
lastUpdateTime = currentTime;
}
}
pls provide code with sample
As i said in the last post of you, you should take a look at the Tutorial!
First of all you do not need to calculate the delta time yourself. I already postet how you get it in the last post for you.
Ill give you a super short example with a moving sprite without flickering.
At first here is the ApplicationListener. (not a GDXtest)
public class MainClass implements ApplicationListener {
private Screen currentScreen = null;
#Override
public void create() {
Texture.setEnforcePotImages(false);
this.currentScreen = new TestScreen();
}
#Override
public void dispose() {
this.currentScreen.dispose();
}
#Override
public void render() {
this.currentScreen.render(Gdx.graphics.getDeltaTime());
}
#Override
public void resize(int width, int height) {
this.currentScreen.resize(width, height);
}
#Override
public void pause() {
this.currentScreen.pause();
}
#Override
public void resume() {
this.currentScreen.resume();
;
}
}
It's preaty simple and as you can see it does call the render of the screen automatically with the delta time! this.currentScreen.render(Gdx.graphics.getDeltaTime()).
The next thing you need is a simple Screen. So something that does implement the Screeninterface. Id really recommand that you use a Scene2D setup with a stage. But here is an example without.
public class TestScreen implements Screen {
private Sprite mySprite;
private SpriteBatch batch = new SpriteBatch();
public TestScreen() {
this.mySprite = new Sprite(new Texture(
Gdx.files.internal("data/appicon.png")));
this.mySprite.setPosition(50f, 50f);
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
this.update(delta);
this.batch.begin();
this.mySprite.draw(batch);
this.batch.end();
}
public void update(float delta) {
if (Gdx.input.isKeyPressed(Keys.D) == true) {
mySprite.setX(mySprite.getX() + 150 * delta);
} else if (Gdx.input.isKeyPressed(Keys.A) == true) {
mySprite.setX(mySprite.getX() - 150 * delta);
} else if (Gdx.input.isKeyPressed(Keys.Z) == true) {
mySprite.setY(mySprite.getY() - 150 * delta);
} else if (Gdx.input.isKeyPressed(Keys.W) == true) {
mySprite.setY(mySprite.getY() + 150 * delta);
}
}
#Override
public void resize(int width, int height) {
}
#Override
public void show() {
}
#Override
public void hide() {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
}
}
Regardas and do take a look at the tutorial. (Here is again the beginning of it)

Categories

Resources