How to use timer with libgdx? - java

I'm trying to use the gdx Timer to increment a value repeatedly but when I use this value inside a Label it seems like nothing happens and the value is stuck at 0 , here is my code for the timer :
#Override
public void show() {
stage = new Stage();
Gdx.input.setInputProcessor(stage);
Skin skin = new Skin(Gdx.files.internal("gui/uiskin.json"));
table = new Table(skin);
table.setFillParent(true);
atlas = new TextureAtlas("gui/atlas.pack");
skin2 = new Skin(Gdx.files.internal("gui/MenuSkin.json"), atlas);
DragAndDrop dragAndDrop = new DragAndDrop();
// My tables
inventoryActor = new InventoryActor(new Inventory(16, 3), dragAndDrop, skin, "Game Pad");
inventoryActor2 = new InventoryActor(new Inventory(25), dragAndDrop, skin, "Inventory Pad");
// bc image
batch = new SpriteBatch();
texture = new Texture(Gdx.files.internal("et2.jpg"));
Timer.schedule(new Task(){
#Override
public void run() {
timing++;
}
}, 1);
heading = new Label("Good Luck"+(timing++), skin2, "big");
//Timer task
//timerCount = new Label("Time : "+timing+" s",skin2, "small");
back = new TextButton("Back", skin2, "small");
back.addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
((Game) Gdx.app.getApplicationListener()).setScreen(new GameOption());
}
});
back.pad(10);
table.add(heading).colspan(3).expandX().spaceBottom(50).row();
table.add(inventoryActor2).uniformX().expandY().top().left().padLeft(30);
table.add(inventoryActor).top().spaceLeft(30);
table.add(back).bottom().right();
stage.addActor(table);
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
/*if (Gdx.input.isKeyPressed(Input.Keys.ANY_KEY)) {
}*/
batch.begin();
batch.draw(texture, 10, 10);
batch.end();
inventoryActor.setVisible(true);
inventoryActor2.setVisible(true);
stage.act(delta);
stage.draw();
}

The problem is, that you never set your Labels text inside the show() method.
You only give it an initial text as a String in the constructor, so the Label doesn't know, that the timing has changed.
So you should set the Labels text in the render() before calling stage.draw().

Related

LibGDX Button in table goes offscreen

Trying to place two buttons in a table row.
Right-most button appears slightly offscreen.
Adding to table with .add(btn).right() but seems not to have any effect.
Documentation says something about removing the Align.left and vise-versa but I'm not sure what they're saying.
Working from mobile.
Took pic, uploaded to ImageBucket but can't see whole thing so took two more (top + bottom of screen) just in case.
Top of screen:
https://i1161.photobucket.com/albums/q501/StudioGilliam/Screenshot_20190430-224041_TextBasedRPG.jpg
As you can see, the labels display fine.
Bottom of screen:
https://i1161.photobucket.com/albums/q501/StudioGilliam/Screenshot_20190430-224024_TextBasedRPG.jpg
The offending code:
public class TextBasedRPG implements ApplicationListener
{
private Stage stage;
private TextButton btnNext;
private TextButton btnItems;
private Label lblPlayer1;
private Label lblEnemy1;
private Label lblInfo;
#Override
public void create()
{
stage = new Stage(new ScreenViewport());
Gdx.input.setInputProcessor(stage);
// UI STUFF
// Labels
Label.LabelStyle styleL = new Label.LabelStyle(new BitmapFont(), Color.BLACK);
lblPlayer1 = new Label("Player data", styleL);
lblPlayer1.setFontScale(3.5f);
lblEnemy1 = new Label("Enemy data", styleL);
lblEnemy1.setFontScale(3.5f);
lblEnemy1.setAlignment(Align.right);
lblInfo = new Label("Information", styleL);
lblInfo.setFontScale(4.0f);
// Buttons
TextButton.TextButtonStyle styleTB = new TextButton.TextButtonStyle();
styleTB.font = new BitmapFont();
styleTB.up = new NinePatchDrawable(new NinePatch(new Texture(Gdx.files.internal("ButtonGreyUp.png")), 10, 10, 10, 10));
styleTB.down = new NinePatchDrawable(new NinePatch(new Texture(Gdx.files.internal("ButtonGreyDown.png")), 10, 10, 10, 10));
btnNext = new TextButton("Next Turn", styleTB);
btnNext.setTransform(true);
btnNext.setScale(6.0f);
btnNext.setTouchable(Touchable.enabled);
btnNext.align(Align.right);
btnItems = new TextButton("Play", styleTB);
btnItems.setTransform(true);
btnItems.setScale(6.0f);
btnItems.setTouchable(Touchable.enabled);
// Table
Table table = new Table();
table.setBounds(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
table.setFillParent(true);
table.pad(50);
table.add(lblPlayer1).expandX().left();
table.add(lblEnemy1).expandX().right();
table.row();
table.add(lblInfo).expandY().colspan(2);
table.row();
table.add(btnItems).expandX().left();
table.add(btnNext).expandX().right();
table.debugAll();
stage.addActor(table);
}
#Override
public void render()
{
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act();
stage.draw();
}
#Override
public void dispose(){stage.dispose();}
#Override
public void resize(int width, int height){}
#Override
public void pause(){}
#Override
public void resume(){}
I don't recommend using setScale() since it only affects the representation of the actor and causes problems with the actual dimensions within the table.
You should use a fitting width and height for your buttons and use a font with a bigger textsize.
You could use GDX Freetype to generate your fonts with the correct size on startup.
Here is an example approach for the solution:
I use the following approach for my UI elements here as an example for a Label:
This is in my static UIHelper Class:
public static Cell addToTable(Table table, Label label, float width) {
Label.LabelStyle style = new Label.LabelStyle(skin.get("default", Label.LabelStyle.class));
float aspectRatio = style.background.getMinWidth()/style.background.getMinHeight();
float height = width / aspectRatio;
style.font = Assets.font;
style.fontColor = Assets.font.getColor();
label.setStyle(style);
label.setAlignment(Align.center);
return table.add(label).width(width).height(height);
}
Then I can just call:
float width = (float)Gdx.graphics.getWidth()*0.8f; // I want my label to be 80% of the screen width
UIHelper.addToTable(table, levelLabel, width).colspan(3).pad(20);
For my fonts, I do this:
private static BitmapFont generateFont(){
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("skins/beemelon/passion-one-regular.ttf"));
FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
parameter.size = (int) (38 * Gdx.graphics.getDensity()); // Change the 38 to a value fit for your game
parameter.color = new Color(255f / 255f, 165f / 255f, 23f / 255f, 1f); // Divide by 255f to get a value between 0 and 1
parameter.borderWidth = parameter.size / 10f;
parameter.borderColor = Color.BLACK;
BitmapFont bitmapFont = generator.generateFont(parameter);
generator.dispose();
return bitmapFont;
}
Hope this helps or pushes you in the right direction.

AndroidStudio libgdx ChangeListener not working

Android Studio-libgdx making a 2d game.
I have a Main which creates the MenuState, in the render method I made this
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0.2f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
myGame.batch.setProjectionMatrix(camera.combined);
batch = new SpriteBatch();
skin = new Skin(Gdx.files.internal("data/uiskin.json"));
stage = new Stage();
final TextButton button = new TextButton("Click me", skin, "default");
button.setWidth(400f);
button.setHeight(100f);
button.setPosition(Gdx.graphics.getWidth() / 2 - 100f, Gdx.graphics.getHeight() / 2 - 10f);
button.addListener(new ChangeListener() {
#Override
public void changed(ChangeEvent event, Actor actor) {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
});
stage.addActor(button);
Gdx.input.setInputProcessor(stage);
myGame.batch.begin();
stage.draw();
myGame.batch.end();
}
I checked some tutorials on how to make a menu and that's pretty much what I'm testing in here.
But when I run the app the button appears and nothing happens if I click it.
I've tried testing with the ClickListener but still doesn't work. Any ideas? Or am I doing it wrong or it should be in another method?
I'm new with libgdx. Thanks in advance.
You are creating new instances of the stage, skin and batch in render method? Move them away from your render method ;)
Render should look more like this:
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0.2f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
myGame.batch.setProjectionMatrix(camera.combined);
myGame.batch.begin();
stage.draw();
myGame.batch.end();
}
And in constructor:
batch = new SpriteBatch();
skin = new Skin(Gdx.files.internal("data/uiskin.json"));
stage = new Stage();
final TextButton button = new TextButton("Click me", skin, "default");
button.setWidth(400f);
button.setHeight(100f);
button.setPosition(Gdx.graphics.getWidth() / 2 - 100f, Gdx.graphics.getHeight() / 2 - 10f);
button.addListener(new ChangeListener() {
#Override
public void changed(ChangeEvent event, Actor actor) {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
});
stage.addActor(button);
Gdx.input.setInputProcessor(stage);

LibGdx Textbutton Listener

Im completly new here and I need some fast help on a Project!!
I use LibGdx to write a little "Risiko" if somebody know it. Im creating a menu and my TextButtons dont work!! Here is the important Part:
stage = new Stage[3];
stage[0] = new Stage();
stage[1]= new Stage();
stage[2]= new Stage();
batch = new SpriteBatch();
setBmap(new Texture("map.png"));
inputMultiplexer=new InputMultiplexer();
inputMultiplexer.addProcessor(this);
inputMultiplexer.addProcessor(stage[0]);
inputMultiplexer.addProcessor(stage[1]);
inputMultiplexer.addProcessor(stage[2]);
Gdx.input.setInputProcessor(inputMultiplexer);
button = new TextButton[8];
//Southamerica
button[0] = new TextButton("Attack", textButtonStyle);
button[0].setBounds(605,463, 100,40);
... Create the buttons.
stage[0].addActor(button[0]);
stage[0].addActor(button[1]);
stage[0].addActor(button[2]);
stage[1].addActor(button[4]);
stage[1].addActor(button[5]);
stage[1].addActor(button[6]);
stage[2].addActor(button[3]);
stage[2].addActor(button[7]);
for(int i= 0; i <= 7 ; i++){
button[i].addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y){
System.out.println("Button action");
}});
}
/*button[0].addListener(new ChangeListener() {
public void changed (ChangeEvent event, Actor actor) {
System.out.println("BUTTOn");
}
});*/
button[0].addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y){
System.out.println("BUTTON PRESSED!!");
}});
Add Buttons to stages and create the Listener!
And now my render() :
super.render();
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
font = new BitmapFont();
batch.begin();
batch.draw(getBmap(), 0, 0);
stage[0].draw();
-
batch.end();
}
I use different Stages do draw different menus. Just for Info :D
And already Thanks for any answer!!
Sorry, for the request now I got it. I didnt got that I have to do it like this:
inputMultiplexer=new InputMultiplexer();
inputMultiplexer.addProcessor(stage[0]);
inputMultiplexer.addProcessor(stage[1]);
inputMultiplexer.addProcessor(stage[2]);
inputMultiplexer.addProcessor(this);
Gdx.input.setInputProcessor(inputMultiplexer);
and not like this:
inputMultiplexer=new InputMultiplexer();
inputMultiplexer.addProcessor(this);
inputMultiplexer.addProcessor(stage[0]);
inputMultiplexer.addProcessor(stage[1]);
inputMultiplexer.addProcessor(stage[2]);
Gdx.input.setInputProcessor(inputMultiplexer);
I love it :D
RIP

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.

java, libgdx - cant get custom font to appear

i have the following class that is suppose to reference a font and then draw a string to the screen once an event has occured. the class is called like this .
if (grumpface.whiteballoon.getBoundingRectangle().overlaps(spriterect)) {
((Game) Gdx.app.getApplicationListener()).setScreen(new GameOverScreen());
}
;
the class it references it this but i still cant get the font to appear any suggestiosns?
class GameOverScreen implements Screen{
private Stage stage;
// Called automatically once for init objects
#Override
public void show() {
stage = new Stage();
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.BLACK);
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);
stage.act(delta);
stage.draw();
}
The font color of your label is getting set to "black", which is the same as your background color.

Categories