Reuse code when using screens in Libgdx - java

From what I understand when reading other peoples code on how to make different screens. You do a main handler class sort of... And then create a new class for each screen.
The thing that confuses me is that whenever you create a new screen, you have to redefine everything that's going to be rendered, like SpriteBatch, sprites, fonts, etc. Is there any way to reuse these kind of things in all screens? I mean, if I have 10 screens, and want to be able to draw text on every screen. Is it really good programming practice to make a new BitmapFont for all 10 screen classes?

I've created an Abstract Screen class that contains all the common objects for a screen, every one of my screens extend this abstract class. And that looks like this:
public abstract class AbstractScreen implements Screen {
protected final Game game;
protected InputMultiplexer multiInputProcessor;
protected ScreenInputHandler screenInputHandler;
protected Stage uiStage;
protected Skin uiSkin;
public AbstractScreen(Game game) {
this.game = game;
this.uiStage = new Stage();
this.uiSkin = new Skin();
this.screenInputHandler = new ScreenInputHandler(game);
this.multiInputProcessor = new InputMultiplexer();
multiInputProcessor.addProcessor(uiStage);
multiInputProcessor.addProcessor(screenInputHandler);
Gdx.input.setInputProcessor(multiInputProcessor);
}
private static NinePatch processNinePatchFile(String fname) {
final Texture t = new Texture(Gdx.files.internal(fname));
final int width = t.getWidth() - 2;
final int height = t.getHeight() - 2;
return new NinePatch(new TextureRegion(t, 1, 1, width, height), 3, 3, 3, 3);
}
#Override
public void render (float delta) {
Gdx.gl.glClearColor(0.2f, 0.2f, 0.2f, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
uiStage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 30f));
uiStage.draw();
Table.drawDebug(uiStage);
}
#Override
public void resize (int width, int height) {
}
#Override
public void show() {
}
#Override
public void hide() {
dispose();
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
uiStage.dispose();
uiSkin.dispose();
}
}
When I want to create a new class I just extend the abstract screen and add what I need. For example I have a basic credits screen, I just need to create the components but the abstract screen draws it:
public class CreditsScreen extends AbstractScreen {
public CreditsScreen(final Game game) {
super(game);
// Generate a 1x1 white texture and store it in the skin named "white".
Pixmap pixmap = new Pixmap(1, 1, Format.RGBA8888);
pixmap.setColor(Color.WHITE);
pixmap.fill();
uiSkin.add("white", new Texture(pixmap));
// Store the default libgdx font under the name "default".
BitmapFont buttonFont = new BitmapFont();
buttonFont.scale(scale);
uiSkin.add("default", buttonFont);
// Configure a TextButtonStyle and name it "default". Skin resources are stored by type, so this doesn't overwrite the font.
TextButtonStyle textButtonStyle = new TextButtonStyle();
textButtonStyle.up = uiSkin.newDrawable("white", Color.DARK_GRAY);
textButtonStyle.down = uiSkin.newDrawable("white", Color.DARK_GRAY);
textButtonStyle.checked = uiSkin.newDrawable("white", Color.BLUE);
textButtonStyle.over = uiSkin.newDrawable("white", Color.LIGHT_GRAY);
textButtonStyle.font = uiSkin.getFont("default");
uiSkin.add("default", textButtonStyle);
// Create a table that fills the screen. Everything else will go inside this table.
Table table = new Table();
table.setFillParent(true);
uiStage.addActor(table);
table.debug(); // turn on all debug lines (table, cell, and widget)
table.debugTable(); // turn on only table lines
// Label
BitmapFont labelFont = new BitmapFont();
labelFont.scale(scale);
LabelStyle labelStyle = new LabelStyle(labelFont, Color.BLUE);
uiSkin.add("presents", labelStyle);
final Label myName = new Label("Credits and all that stuff", uiSkin, "presents");
table.add(myName).expand().center();
}
}
I also have a single class that handles the input for all the screens, the specific purpose for this is to handle how the back button works around the different screens. And this input handler class is created in the abstract class.
public class ScreenInputHandler implements InputProcessor {
private final Game game;
public ScreenInputHandler(Game game) {
this.game = game;
}
#Override
public boolean keyDown(int keycode) {
if(keycode == Keys.BACK || keycode == Keys.BACKSPACE){
if (game.getScreen() instanceof MainMenuScreen) {
Gdx.app.exit();
}
if (game.getScreen() instanceof GameScreen) {
World.getInstance().togglePause(false);
}
if (game.getScreen() instanceof CreditsScreen) {
game.setScreen(new MainMenuScreen(game));
}
}
return false;
}
}

Related

libGDX: How to read and display text from a .txt file line by line after pressing a key?

I'm new to Java and I'm trying to make a Visual Novel type of game.
What I'm trying to do is display text from a text file line by line by pressing a space button, like in a usual novel.
I've overlooked different methods but nothing works out for me. I know there are Scanner and BufferedReader, but are they suitable for what I'm doing?
Right now all that happens is when I press "space" the whole text appears on the screen, and when I let go, it dissapears.
This is my game class:
public class NovelGame extends Game {
public static final int WIDTH = 1366;
public static final int HEIGHT = 768;
public SpriteBatch batch;
public String txtFileString;
public String lines[];
public BitmapFont bitmapFont;
#Override
public void create () {
batch = new SpriteBatch();
bitmapFont = new BitmapFont();
this.setScreen(new MainMenuScreen(this));
txtFileString = Gdx.files.internal("script.txt").readString();
String[] anArray = txtFileString.split("\\r?\\n");}
#Override
public void render () {
super.render();
}}
This is my game screen class:
public class MainGameScreen implements Screen{
private Texture img;
NovelGame game;
public MainGameScreen (NovelGame game) {
this.game = game;
}
#Override
public void show() {
img = new Texture("bck.jpg");
}
#Override
public void render(float delta) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // This cryptic line clears the screen.
game.batch.begin();
game.batch.draw(img, 0, 0);
if(Gdx.input.isKeyPressed(Input.Keys.SPACE)){
game.bitmapFont.draw(game.batch, game.txtFileString,Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight()/2);
}
game.batch.end();
}
I had an idea to display it using while and if, but can't exactly figure out how to do it.
EDIT: I found a way to display text, but now, once I run my game, it starts piling one on another endlessly after I press space.
Code:
public class MainGameScreen implements Screen{
private Texture img;
NovelGame game;
public MainGameScreen (NovelGame game) {
this.game = game;
}
#Override
public void show() {
img = new Texture("bck.jpg");
}
#Override
public void render(float delta) {
try {
BufferedReader br = new BufferedReader (new FileReader("C:\\Users\\hydra\\Documents\\JAVA_PROJECTS\\gamespace\\core\\assets\\startd.txt"));
while((game.strLine = br.readLine()) != null){
game.list.add(game.strLine);
}
br.close();
} catch (IOException e) {
System.err.println("Unable to read the file.");
}
if(Gdx.input.isKeyJustPressed(Input.Keys.SPACE)){
game.showText = true;
}
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // This cryptic line clears the screen.
game.batch.begin();
game.batch.draw(img, 0, 0);
if(game.showText) {
for(int i = 0; i < game.list.size(); i++) {
System.out.println(game.list.get(i));
game.bitmapFont.draw(game.batch, game.list.get(i), 100, 50);
}
}
game.batch.end();
}
Problem is here. Gdx.input.isKeyPressed returns true if only key is pressing currently.
if(Gdx.input.isKeyPressed(Input.Keys.SPACE)){
game.bitmapFont.draw(game.batch, game.txtFileString,Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight()/2);
}
To fix this add a boolean flag activate it after key is only just pressed:
if(Gdx.input.isKeyJustPressed(Input.Keys.SPACE)){
showText = true;
}
And in render method:
if (showText) {
game.bitmapFont.draw(game.batch, game.txtFileString,Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight()/2);
}
I found out what I was doing wrong in the end. I put everything in render method, and that's why file was being read endlessly. I need to do it only once in the constructor class and then put it in the render method.

How to extend Actor and draw it on stage? Libgdx

I am trying to make an object that extends the Actor class. but whenever I have call the Stage's draw() method, it only draws the button I added to it. Here is my code, maybe someone here can help me?
Code for my Screen class (Assume that I had overridden all necessary methods and that I imported all necessary classes):
public class PlayScreen implements Screen{
SpriteBatch batch;
Game game;
Table table;
Skin skin;
Stage stage;
BitmapFont font;
TextButton button;
TextDisplay display;
public PlayScreen(MyGdxGame game, SpriteBatch batch){
this.game = game;
this.batch = batch;
//instantiating Stage, Table, BitmapFont, and Skin objects.
font = new BitmapFont(Gdx.files.internal("MyTruefont.fnt"));
table = new Table();
stage = new Stage();
skin = new Skin(Gdx.files.internal("Test.json"));
button = new TextButton("Start!", skin, "default");
display = new TextDisplay(font, this);
//Setting table properties
table.setWidth(stage.getWidth());
table.align(Align.center|Align.top);
table.setPosition(0, Gdx.graphics.getHeight());
table.padTop(30);
//Adding actors to table
table.add(button).padBottom(50);
table.add(display);
//Adding table to stage and setting stage as the input processor
stage.addActor(table);
Gdx.input.setInputProcessor(stage);
}
#Override
public void show() {
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
stage.draw();
batch.end();
}
And here is My Textdisplay class that extends Actor (Again assume all other methods have been overriden, and all necessary classes have been imported):
public class TextDisplay extends Actor implements Drawable {
Texture texture;
BitmapFont font;
String str;
public TextDisplay(BitmapFont font, Screen screen){
this.font = font;
texture = new Texture(Gdx.files.internal("TextArea.png"));
str = "";
setLeftWidth(texture.getWidth());
setRightWidth(texture.getWidth());
setBottomHeight(texture.getHeight());
setTopHeight(texture.getHeight());
}
#Override
public void draw(Batch batch, float x, float y, float width, float height) {
batch.draw(texture, x, y);
}
You overrode the wrong draw method. Actor's draw method signature is:
public void draw (Batch batch, float parentAlpha)
You overrode the one from Drawable. Not sure why you're implementing Drawable. There's already an Actor available for drawing text anyway, called Label.
Also, if you want to put your Actor in a table, you need to set its width and height, or the width and height of its cell in the table.

Problems rendering map position with LibGDX

I've been following along with a LibGDX tutorial on Youtube and have come across an issue rendering a TiledMap to my screen. At the moment, I can render some labels/images using my HUD java class
public class HUD {
public Stage stage; //the background
private Viewport viewport; //so the HUD stays fixed and the world can move
private int score;
private int timer;
private int bactoCount;
private Texture foodTexture, antioBioBottle;
//these are widgets
Label antioBioTxt;
Image antiBioImg;
Label countDown;
Label countTxt;
Image foodImg;
Label foodTxt;
Label bactoCountLabel;
Label bactoTxt;
//these images need to be buttons...
public HUD (SpriteBatch sb) {
foodTexture = new Texture("Bacto food.png");
antioBioBottle = new Texture("Antibioticbottle.png");
bactoCount = 0;
timer = 0;
viewport = new FitViewport(BactoBuds.V_WIDTH, BactoBuds.V_HEIGHT, new OrthographicCamera());
stage = new Stage(viewport, sb);
//stage = new Stage();
//use a Table to organise widgets on the stage
Table table = new Table();
table.top();
table.setFillParent(true); //the table is the size of our stage
antioBioTxt = new Label("Antibiotic", new Label.LabelStyle(new BitmapFont(), Color.WHITE));
antiBioImg = new Image(antioBioBottle);
// %03d means its 3 digits long
//bitmap font sets the font to bit style
//string.format for changing from a string to a int
countDown = new Label(String.format("%03d", timer), new Label.LabelStyle(new BitmapFont(), Color.WHITE));
countTxt = new Label("Time to flood:", new Label.LabelStyle(new BitmapFont(), Color.WHITE));
foodImg = new Image(foodTexture);
foodTxt = new Label("Food", new Label.LabelStyle(new BitmapFont(), Color.WHITE));
bactoCountLabel = new Label(String.format("%06d", bactoCount), new Label.LabelStyle(new BitmapFont(), Color.WHITE));
bactoTxt = new Label("Bacteria:", new Label.LabelStyle(new BitmapFont(), Color.WHITE));
//if multiple labels use expandX then they all share an equal portion of the screen
table.add(antioBioTxt).expandX().padTop(10);
table.add(foodTxt).expandX().padTop(10);
table.add(bactoTxt).expandX().padTop(10);
table.add(countTxt).expandX().padTop(10);
table.row();
table.add(antiBioImg).expandX();
table.add(foodImg).expandX();
table.add(bactoCountLabel).expandX().align(Align.center);
table.add(countDown).expandX().align(Align.center);
stage.addActor(table);
}
}
These render nicely on the screen. However, when I try to render up a background TMX map image, it renders in the wrong location. I've been messing with the code for a few days now, trying to change the position of the map position. At the first instance I was only able to see a tiny corner of the map and now I've gotten the whole thing to render, but it only takes up ~1/4 of the screen. Now I am at a loss as to how to proceed.
public class playScreen implements Screen{
private BactoBuds game;
private OrthographicCamera gamecamera;
private Viewport gameView;
private HUD HUD;
private TmxMapLoader mapLoader; //loads map to screen
private TiledMap map; //reference to map
private OrthogonalTiledMapRenderer renderer;
public playScreen (BactoBuds game) {
this.game = game;
gamecamera = new OrthographicCamera();
gameView = new FitViewport(BactoBuds.V_WIDTH, BactoBuds.V_HEIGHT, gamecamera);
HUD = new HUD(game.batch);
mapLoader = new TmxMapLoader(); //make a new map loader, set map to maploader, then pass it to the renderer
map = mapLoader.load("grassy.tmx");
renderer = new OrthogonalTiledMapRenderer(map);
gamecamera.setToOrtho(false);
gamecamera.position.set(gameView.getWorldWidth() / 2, gameView.getWorldHeight() / 2, 0); //this changes map position
renderer.setView(gamecamera);
}
#Override
public void show() {
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
renderer.render();
game.batch.setProjectionMatrix(HUD.stage.getCamera().combined);
HUD.stage.draw();
}
Please forgive the dodgy coding, I'm quite new and I'm still learning about good practices. I think it has something to do with the camera positioning, but swapping out the values doesn't appear to change anything.
public class BactoBuds extends Game {
public static final int V_WIDTH = 800;
public static final int V_HEIGHT = 480;
public static final String Title = "BactoBuds";
public SpriteBatch batch; //public to let other screens have access to images
private Texture img;
private Game game;
private Screen screen;
private OrthographicCamera camera;
public BactoBuds () {
game = this;
}
#Override
public void create () {
batch = new SpriteBatch();
img = new Texture("badlogic.jpg");
// change this to menuScreen later
setScreen(new playScreen(this));
}
public void dispose () {
batch.dispose();
img.dispose();
}
#Override
public void render () {
super.render();
}
public void resume (){
}
public void pause () {
}
}
Thanks for the help!
You need to call camera.update() within render method.
Have you tried moving your camera? If only 1/4 of the map is visible your camera might be centered at 0,0 while your map uses that as the bottom left origin of the texture.
Try camera.position.set(BactoBuds.V_WIDTH / 2, BactoBuds.V_HEIGHT / 2, 0);

Atlas does not render images in order[libGDX]

I am using the following class to render an atlas on screen:
public class AnimationDemo implements ApplicationListener {
private SpriteBatch batch;
private TextureAtlas textureAtlas;
private Animation animation;
private float elapsedTime = 0;
#Override
public void create() {
batch = new SpriteBatch();
textureAtlas = new TextureAtlas(Gdx.files.internal("data/packOne.atlas"));
animation = new Animation(1 / 1f, textureAtlas.getRegions());
}
#Override
public void dispose() {
batch.dispose();
textureAtlas.dispose();
}
#Override
public void render() {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
//sprite.draw(batch);
elapsedTime += Gdx.graphics.getDeltaTime();
batch.draw(animation.getKeyFrame(elapsedTime, true), 0, 0);
batch.end();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
I am a beginner with libGDX, however with the above program my images are not rendered in order as random images appear. I was earlier using the following with the same . atlas file and it was working properly:
public class MyGdxGame implements ApplicationListener {
private SpriteBatch batch;
private TextureAtlas textureAtlas;
private Sprite sprite;
private int currentFrame = 1;
private String currentAtlasKey = new String("0001");
#Override
public void create() {
batch = new SpriteBatch();
textureAtlas = new TextureAtlas(Gdx.files.internal("data/packOne.atlas"));
TextureAtlas.AtlasRegion region = textureAtlas.findRegion("0001");
sprite = new Sprite(region);
sprite.setPosition(Gdx.graphics.getWidth() / 2 - sprite.getWidth() / 2, Gdx.graphics.getHeight() / 2 - sprite.getHeight() / 2);
sprite.scale(4.5f);
Timer.schedule(new Timer.Task() {
#Override
public void run() {
currentFrame++;
if (currentFrame > 393)
currentFrame = 1;
// ATTENTION! String.format() doesnt work under GWT for god knows why...
currentAtlasKey = String.format("%04d", currentFrame);
sprite.setRegion(textureAtlas.findRegion(currentAtlasKey));
}
}
, 0, 1 / 30.0f);
}
#Override
public void dispose() {
batch.dispose();
textureAtlas.dispose();
}
#Override
public void render() {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
sprite.draw(batch);
batch.end();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
Any hints about what might be wrong here?
I am also trying to adapt my program with Screen Viewport any headings as in how to implement this would also be welcome.
Edit: The .atlas file is located here
Your atlas file isn't ordered. If you call the code below, it will be ordered.
regions.sort(new Comparator<AtlasRegion>() {
#Override
public int compare(AtlasRegion o1, AtlasRegion o2) {
return Integer.parseInt(o1.name) > Integer.parseInt(o2.name) ? 1 : -1;
}
});
But I'm still checking why your atlas regions isn't ordered.
you should create array with frames ordered alphabetically instead of using textureAtlas.getRegions() which just gives you an array without caring of order.
The example for atlas with regions named like: region1, region2 and so on would be:
AtlasRegion[] frames = new AtlasRegion[framesCount];
for(int i = 0; i < framesCount; i++)
{
frames[i] = atlas.findRegion("region" + i);
}
so you can adjust it to your regions names.
If you want to get all frames from textureAtlas you can also do it like this:
Array<String> names = new Array<String>();
for(AtlasRegion region : textureAtlas.getRegions())
{
names.add( region.name );
}
names.sort();
Array<AtlasRegion> frames = new Array<AtlasRegion>();
for(String s : names)
{
frames.add( textureAtlas.findRegion(s) );
}
and then after get frames array just create animation object:
animation = new Animation(1/1f, frames.items); //or just frames depending on which type frames is
TexturePacker will index the images for you as long as you follow the naming scheme set forth here https://github.com/libgdx/libgdx/wiki/Texture-packer#image-indexes.
so your frames would be named something like
anim1_001.png
anim1_002.png
...
anim1_100.png
and a separate animation would simply be
anim2_001.png
....
anim2_100.png
EDIT:
additionally you can get the regions only related to certain animations. So instead of
animation = new Animation(1 / 1f, textureAtlas.getRegions());
you could use (yes it's findRegions() not findRegion()):
animation1 = new Animation(1 / 1f, textureAtlas.findRegions("anim1"));
animation2 = new Animation(1 / 1f, textureAtlas.findRegions("anim2"));
EDIT2:
If you're are using a stage it is quite easy to implement a screen viewport. I do it like this, (stage is a field and this step is in the show/create method):
stage = new Stage(new ScreenViewport());
Then in the resize method:
stage.getViewport().update(width, height, true);
Without a stage it's only slightly more complex
camera = new WhateverCamera();
viewport = new ScreenViewport(camera);
Then in the resize method:
viewport.update(width, height, true);
Use whatever camera you want, WhateverCamera is a placeholder and can be OrthographicCamera or PerspectiveCamera.
The last argument true centers the camera, if you don't want to do this set it to false or leave it out, it assumes false.

LIBGDX creating actors and stage for the main menu

I need to know how i would go about setting up a stage and adding actors to it for my main menu.
Here is my code so far
public class MainMenu implements Screen {
CrazyZombies game;
Stage stage;
TextureAtlas atlas;
SpriteBatch batch;
Skin skin;
Button button;
TextureRegion firstLayer, secondLayer, thirdLayer, fourthLayer,
fifthLayer, sixthLayer, seventhLayer, eighthLayer, ninthLayer,
tenthLayer, eleventhLayer;
Sprite road, backTrees, sideTrees, bottemTrees, light, poles,
play, quit, store, custom, options;
public MainMenu(CrazyZombies game){
this.game = game;
}
#Override
public void render(float delta) {
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
Gdx.gl.glClearColor(0.09f, 0.28f, 0.2f, 1);
batch.begin();
road.draw(batch);
backTrees.draw(batch);
sideTrees.draw(batch);
bottemTrees.draw(batch);
light.draw(batch);
poles.draw(batch);
play.draw(batch);
quit.draw(batch);
store.draw(batch);
custom.draw(batch);
options.draw(batch);
batch.end();
}
#Override
public void resize(int width, int height) {
Gdx.input.setInputProcessor(stage);
}
#Override
public void show() {
Audio.playMusic(true);
batch = new SpriteBatch();
atlas = new TextureAtlas("data/mainmenu/MainMenu.pack");
firstLayer = atlas.findRegion("1layer");
secondLayer = atlas.findRegion("2layer");
thirdLayer = atlas.findRegion("3layer");
fourthLayer = atlas.findRegion("4layer");
fifthLayer = atlas.findRegion("5layer");
sixthLayer = atlas.findRegion("6layer");
seventhLayer = atlas.findRegion("7layer");
eighthLayer = atlas.findRegion("8layer");
ninthLayer = atlas.findRegion("9layer");
tenthLayer = atlas.findRegion("10layer");
eleventhLayer = atlas.findRegion("11layer");
road = new Sprite(firstLayer);
backTrees = new Sprite(secondLayer);
sideTrees = new Sprite(thirdLayer);
bottemTrees = new Sprite(fourthLayer);
light = new Sprite(fifthLayer);
poles = new Sprite(sixthLayer);
play = new Sprite(seventhLayer);
quit = new Sprite(eighthLayer);
store = new Sprite(ninthLayer);
custom = new Sprite(tenthLayer);
options = new Sprite(eleventhLayer);
}
#Override
public void hide() {
dispose();
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
batch.dispose();
atlas.dispose();
Audio.dispose();
}
}
The bits that i need to become actors are:
- play
- quit
- store
- custom
- options
All my code does at the moment is just display my main menu i need to get the stage and actors setup in order to get the buttons working.
Take a look at TableLayout and also take a look at TextButton or maybe Button.
Here is a good tutorial. Work through it and you will understand how to work with the Screen2D and how to create a simple menu. -> Direkt link to Menucreation of the Blog

Categories