Quantcast
Channel: Question and Answer » libgdx
Viewing all 434 articles
Browse latest View live

LibGDX Json not parsing full file

$
0
0

I’m trying to load a World with different Objects (World Objects and Entities). For that, I want to use Json. For less than two elements this works like a charm. But as I add more elements, some values are skipped on parsing. I’m using LibGDX for my game. Here is my code:

level001.json

{
  "id":1,
  "title":"Broken Home",
  "design":"tomschneider",
  "tiles_x":32,
  "tiles_y":32,
  "objects":[
    {
      "class":"net.sutomaji.space2.helperclasses.LevelStore_Object",
      "object_name":"net.sutomaji.space2.gamelogic.objects.BlackHole",
      "pos_x":10,
      "pos_y":10
    },
    {
      "class":"net.sutomaji.space2.helperclasses.LevelStore_Object",
      "object_name":"net.sutomaji.space2.gamelogic.objects.BlackHole",
      "pos_x":10,
      "pos_y":15
    },
    {
      "class":"net.sutomaji.space2.helperclasses.LevelStore_Object",
      "object_name":"net.sutomaji.space2.gamelogic.objects.SpaceStation",
      "pos_x":0,
      "pos_y":0,
      "i1":0
    },
    {
      "class":"net.sutomaji.space2.helperclasses.LevelStore_Object",
      "object_name":"net.sutomaji.space2.gamelogic.objects.SpaceStation",
      "pos_x":5,
      "pos_y":0,
      "i1":1
    }
  ],
  "entities":[

  ]
}

Excerpt of Level.java

Json json = new Json();
        LevelStore ls = json.fromJson(LevelStore.class, Gdx.files.internal("Worlds/level001.json"));

        System.out.println(json.prettyPrint(ls));

System.out

{
tiles_x: 32,
entities: [],
objects: [
    {
        object_name: net.sutomaji.space2.gamelogic.objects.BlackHole,
        pos_x: 10,
        pos_y: 10
    },
    {
        object_name: net.sutomaji.space2.gamelogic.objects.BlackHole,
        pos_x: 10,
        pos_y: 15
    },
    {
        object_name: net.sutomaji.space2.gamelogic.objects.SpaceStation
    },
    {
        i1: 1,
        object_name: net.sutomaji.space2.gamelogic.objects.SpaceStation,
        pos_x: 5
    }
],
title: "Broken Home",
id: 1,
design: tomschneider,
tiles_y: 32
}

So I am loosing positions (pos_x etc.) and other values (i1) on parsing. I don’t know why. Do you have any ideas?

LibGDX API Json


Why do my images take 200 MB of RAM when they are ~20KB on disk?

$
0
0

I am creating an Android game using libGDX. When I load my nine images it takes 200 MB of RAM. But the images are 10 to 17 KB each. Why the discrepancy? Here is where I create textures from those images:

public static HashMap<String, Texture> ground = new HashMap<String, Texture>();
for (int i = 1; i < 10; i++) {
  ground.put(
  "ground" + i,
    new Texture(Gdx.files.internal("groundImages/ground" + i + ".png"))
  );
}

TiledMap not drawing completely [closed]

$
0
0

While attempting to constrain camera scrolling to within the TiledMap I discovered that it seems the renderer for the map is not drawing the entire map. The map is 1600x960px so one would assume the setting the camera position to 1600, 960, 0 would result in the top right corner of the map to be centered, however to actually center the map (I had to do some trial and error for this) the coordinates are closer to 1175, 740, 0.

The map is made of 25×15 tiles and each tile is 64x64px. I initialize the map and renderer like this:

    tileMap = new TmxMapLoader().load("maps/" + file);
    renderer = new OrthogonalTiledMapRenderer(tileMap, stage.getBatch());
    renderer.setView((OrthographicCamera) stage.getCamera());

Then to render I just call renderer.render().

Any idea why this could be happening and how to fix it?

How can I use imprecise accelerometer data for controls?

$
0
0

I want to rotate an object with respect to the phone’s position. I use the accelerometer output to detect orientation:

float roll = Gdx.input.getRoll();
float pitch = Gdx.input.getPitch();
float azimuth = Gdx.input.getAzimuth();

Vector3 accel=new Vector3(accelX, accelY, accelZ);
bat.transform.setToRotation(0f, -1f, 0f, pitch);

bat.transform.setFromEulerAngles(azimuth, -pitch, -roll);

However, the accelerometer data fluctuates so strongly that the object jitters.

How can I deal with this?

“Pixel-perfect” camera positioning in 2d game

$
0
0

I am writing a 2d game using LibGDX. The view to the game world is top-down. The game shows a grid of lines, which looks nice when the camera is at its initial position (0,0).

The problem is now that when I move (shift) the camera left/right/up/down this grid sometimes becomes a bit blurry, so the lines do not look perfectly sharp any more.

I assume this is because in these cases the grid lines are not exactly on screen pixels, but somewhere in between. Is this correct?

In any case: Are there any “best practices” how to address this problem (not necessarily LibGDX-specific)?

Libgdx desktop windows resize

$
0
0

I have tried to make game with libgdx

I want to create 3×3 grid in the middle of screen
I ran the desktop project, it seems that not much problem at all,
but if I resize the windows the 3×3 grid move towards the lower left of the screen
(I want to make it always in the center of screen regardless of the screen size change)

What are the problem in my code, I am a new to game developing.

public class GameScreen implements Screen {

    MyGdxGame game;
    SpriteBatch batch;
    Texture img, item;

    public GameScreen(MyGdxGame game) {
        this.game = game;

        batch = new SpriteBatch();
        // a 640x480 image for testing background position
        img = new Texture(Gdx.files.internal("640Wx480H.png"));
        // a 64x64 image for grid item
        item = new Texture(Gdx.files.internal("badlogic.jpg"));
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        Gdx.gl.glClearColor(1, 1, 1, 1);
        batch.begin();
        batch.draw(img, 0, 0);
        float itemSize = item.getWidth();
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                batch.draw(item, itemSize * i + (Gdx.graphics.getWidth() - (itemSize * 3)) / 2, itemSize * j + (Gdx.graphics.getHeight() - (itemSize * 3)) / 2);
            }
        }

        batch.end();
    }

    @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() {
        img.dispose();
        item.dispose();
    }

}


public class MyGdxGame extends Game {

    GameScreen mainGameScreen;
    private Viewport viewport;
    private OrthographicCamera camera;

    @Override
    public void create() {
        camera = new OrthographicCamera();
        camera.setToOrtho(false, 640, 480);
        viewport = new FitViewport(640, 480, camera);
        mainGameScreen = new GameScreen(this);
        setScreen(mainGameScreen);
    }

    public void resize(int width, int height) {
        viewport.update(width, height);

    }

    public void render(float delta) {
    }

    public void dispose() {

    }
}

Timer.schedule(task, 0, 100) never fires

$
0
0

I added some code using java.util.Timer to execute my spawnMonster function every 100ms. It worked, until I tried instantiating images in it — since it doesn’t run on the libGDX core thread, there’s no OpenGL context, so it can’t do stuff with images.

I figured using the libGDX Timer class, which the javadocs say runs on the core thread, would solve this problem; but unfortunately, the timer code just doesn’t execute.

I tried:


- new Timer().scheduleTask(task, 0, 100)
- new Timer().scheduleTask(task, 0, 100, 99999)
- Timer.schedule(task, 0, 100)
- Timer.schedule(task, 0, 999999)
- Timer.start()
- t = new Timer(); t.scheduleTask(...); t.start();

task appears to execute once, and only once; it never executes again. (It prints a date-time diff from a target time, so I can tell it’s not running.)

In libgdx, how do I get the intersection of a ray with a model instance?

$
0
0

I am using LibGDX trying to use raypicking to pick a point on a Mesh. I have two methods for this that don’t seem to work quite right:

/**
 * @param ray 
 * @param intersection The vector to store the intersection result
 * @return
 */
public boolean intersect(Ray ray, Vector3 intersection) {
    final BoundingBox bb = new BoundingBox();
    for (int i = 0; i < modelInstances.size; i++) {
        ModelInstance instance = modelInstances.get(i);
        instance.calculateBoundingBox(bb).mul(instance.transform);
        if (Intersector.intersectRayBoundsFast(ray, bb)) {
            return intersect(ray, models.get(i), instance.transform, intersection);
        }
    }
    return false;
}

private boolean intersect(Ray ray, Model model, Matrix4 transform, Vector3 intersection) {
    final Matrix4 reverse = new Matrix4(transform).inv();
    for (Mesh mesh : model.meshes) {
        mesh.transform(transform);
        float[] vertices = new float[mesh.getNumVertices() * 6];
        short[] indices = new short[mesh.getNumIndices()];
        mesh.getVertices(vertices);
        mesh.getIndices(indices);
        try {
            if (Intersector.intersectRayTriangles(ray, vertices, indices, 4, intersection)) {
                intersection.mul(transform);
                return true;
            }
        } finally {
            mesh.transform(reverse);
        }
    }
    return false;
}

The first method calculates if the ray intersects the bounding box of each mesh, if an intersection is found, the second method should calculate exactly where the intersection occurs.

The models I am checking right now are chunks of a terrain created with a height map. It seems that both methods have mistakes in them.

In the second method, I apply the transformation of the model instance to the mesh (since the mesh’s themselves do not have any transformations. After calculating the intersection I transform the mesh with the inverse (which works).

Is there something I am missing here? The method that calculates the bounding boxes seems to always have false positives, also the intersection results are always incorrect.

How do I correctly intersect with bounding boxes?
How to consider transformations when checking intersections with the meshes?
Are the intersection results the world coordinates for the intersection?
How do I check for the closest intersection when there are multiple intersections with the mesh?


Why do my Box2D bodies occasionally get stuck and separate forcibly?

$
0
0

I’m making a space game with LibGDX and Box2D. I made a video here to illustrate the issue.

Verbal description: When objects collide, they sometimes get stuck together and are then suddenly separated by a strong force.

Both objects have identical body definitions and fixtures:

bod = new BodyDef();
bod.type       = type;
bod.allowSleep = false;

shape = new CircleShape();
shape.setRadius(values[0]);

fix = new FixtureDef();
fix.restitution = 0f;
fix.friction    = 1f;
fix.shape       = shape;
fix.density     = 1f;

worldBod = world.createBody(bod);
worldBod.setTransform(position.x, position.y, 0);
worldBod.createFixture(fix);

Why might this be happening? How can I fix it?

Update: Here is some more info.

The Player class contains a function update(float deltaTime) with the rest listed below

force.x += (directionVector.x * SPEED)*deltaTime;
force.y += (directionVector.y * SPEED)*deltaTime;


//This helps keep the object in control from preventing forces greater then 3
if(force.x >= 3){
    force.x = 3;
}if(force.x <= -3){
    force.x = -3;
}if(force.y >= 3){
    force.y = 3;
}if(force.y <= -3){
    force.y = -3;
}
//This quickly reduces the force back down to 0
force.x *= 0.5;
force.y *= 0.5;

this.getBody().applyForceToCenter(force, true); 

In the render part of the main game class I step the world with

gameWorld.step(Gdx.graphics.getDeltaTime(), 6, 6);
//although increasing or decreasing the itterations seems not to help

and Finally the hexagon’s are created using the ShapeRenderer pulling the position and

sr.setProjectionMatrix(camera.combined);
sr.begin(ShapeType.Line);
sr.circle(p1.getBody().getPosition().x, p1.getBody().getPosition().y, 1);
sr.circle(barrierPole.getBody().getPosition().x, barrierPole.getBody().getPosition().y, 1);
sr.end();

Problem with changing font color in libgdx

$
0
0

I recently noticed that my version of libgdx was way out of date, so I updated from version .9.something to 1.4.1. I copied files for the project I’m working on over into a new project generated with the new setup gui and everything works fine except that now all of my text is black, whereas previously it was mostly white. My code hasn’t changed at all.

font = new BitmapFont(Gdx.files.internal("data/vistor.fnt"), false);
font.setColor(Color.WHITE);
font.setScale(5);

...

font.setColor(Color.WHITE);
font.setScale(5);
font.draw(batch, "Score: " + score, 10, 85);
font.draw(batch, "EHP: " + sp, 10, 30);

With this code, the text shows up black. Has something changed with the way fonts work? I’m very confused. The .fnt’s related .tga has white characters on a black background. Any ideas?

LibGdx Input data in a textfield

$
0
0

I have a textfield using scene2d but don’t know how to save user input. this is what i have and it just draws the textfield.

     txtUsername = new TextField("", mSkin);
     txtUsername.setMessageText("test");
     txtUsername.setPosition(30, 30);
     mStage.addActor(txtUsername);

How do I handle game lag due to background apps

$
0
0

I’m developing a game using libgdx and have noticed on several occasions that other background apps running can cause lag in my game – especially when those apps are being updated in the background. I’m talking serious lag like from 50-60 fps down to under 10 fps while the other app installs.

How should I handle this very noticeable lag?

Thanks!

LibGDX: Making an object move correctly based on real time

$
0
0

Below is an image of my gameworld. As we can see, the player starts at position 0. each cell represents 1 game world unit. My goal is to get the player to move 1 unit (the red cell) in 1 second in ‘real world’ time using the LIBGDX framework.

enter image description here

LibGDX uses something called ‘continuous rendering’ by default, which means its ‘main loop’ runs as fast as the underlying OS is able to. The range could be anywhere from 0-80 frames per second. I am capping the FPS to 60 with the below ‘main’ loop (In LIbGDX the main loop is called render)

@Override
public void render(float deltaTime) {

    /*
     * Get the time it took to render the last frame and make sure our delta
     * time is never larger than 0.0166666666666667 (60 FPS). This will
     * ensure that on fast OS the game at only 60 FPS.
     */
    float dt = Math.min(Gdx.graphics.getDeltaTime(), 1 / 60f);

    // **********************UPDATE*********************

    player.update(dt);


    // ************************RENDER********************

    // clear the screen and set it to cornflower blue
    Gdx.gl.glClearColor(0x64 / 255.0f, 0x95 / 255.0f, 0xed / 255.0f,
            0xff / 255.0f);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    worldRenderer.render();


}

Below is the code for my player object’s update method. As we can see it is operating solely on the delta time for now. In a perfect world of 60 FPS, this would work perfectly but unfortunatly FPS dips will always happen (especially on mobile platforms). How can I add a calculation on top of the delta time to move the player 1 unit in real time regardless of framerate?

@Override
public void update(float deltaTime) {

    // handle user input **always should come first**
    if (Gdx.input.isKeyPressed(Keys.SPACE)) {
        position.x += deltaTime;
    }

}

Below shows what is happening with my current code, if we had a perfect 60 FPS the position should = 1, but as we can see it does not because the FPS varies slightly from frame to frame.

enter image description here

libGdx Window .pack() not working

$
0
0

I’m trying to make a window, then use the pack method to get the right size, but the window maximizes instead. Here’s my code:

private Table buildOptionsWindowLayer() {
    winOptions = new Window("Options", skinLibgdx);
    // (...) building some widgets

    Gdx.app.log(TAG, "pref width is " + winOptions.getPrefWidth());
    // displays: "pref width is 247.0"

    winOptions.pack();

    // move the window
    winOptions.setPosition(Constants.VIEWPORT_GUI_HEIGHT - winOptions.getWidth() - 50, 50);
    return winOptions;
}

The window ends up with a width of 800.0f. Why?

What it is supposed to render:
enter image description here

What it does render:
enter image description here

Vertical Text – Bitmap Font Libgdx

$
0
0

vertical
How can I achieve this kind of rotation or vertical text using Bitmap Font?

I already used Matrix but didn’t get the result same as above.


Infinite Jumper Snow Effect

$
0
0

I wish to achieve a snowing effect on my game. The game is made in LibGDX and im using ParticleEmitter. I created a snow effect in ParticleEditor which consists in a line which spawns snow flakes. The problem is:

First, and the most important, since the game movement is vertical (its a jumper), if i just place the line above the screen, the jumping makes it look unnatural since when im jumping up, and the camera follows me, the particle emitter also has to move up, and the snow flakes are spawned with a bigger vertical distance; And when Im going down from the jump, a section of closer snowflakes is spawned due to that occurence. That makes the snow visually inconsistent.

Second, i wanted the snow to show up filling the screen from the start, instead of it starting to follow when the emitter is started.

To try to fix the first problem, i made the snow screen static, but it looks horrible, i really want the feeling that the snow is falling and my character is going up against it.

Any ideas how to achieve such an effect?

Word game – board implementation?

$
0
0

I’m working on a boggle type game for android, using libgdx. The user is presented with a 4×4 grid of letters and must find words by dragging their finger over the letters.

Unlike boggle I want used letters to disappear. Remaining letters will fall down (to the bottom of the board, screen orientation is fixed) and the board is refilled from the top. Users can rotate the board to try and put hard to use letters in a better place by strategic word selection.

An example:

d g a o
u o r T
h v R I
d G n a

If i selected the word GRIT, those letters would disappear and the remaining fall down:

d
u g a
h o r o
d v n a

and then get replaced by new letters

d w x y
u g a z
h o r o
d v n a

I’m stuck figuring out how to represent the board and tiles.

I tried representing the board as a matrix to keep track of tiles selected and valid moves and the tiles stored in a matrix as well so that there was an easy mapping. This works, but I had to write some convoluted code to rotate the board.

How do other games handle this problem?

EDIT:
So thinking about it, I should really just process my touch point according to the board rotation so cells stay constant. Attached an image of what I’m thinking.Process screen touch so board orientation never changes

[LibGdx]Moving a fixture on a body

$
0
0

I’m working with Box2D and I have a basic platform and a box bounces off of it.

// Static Platform
    bdef.position.set(160 / PPM, 120 / PPM);
    bdef.type = BodyType.StaticBody;
    Body b = world.createBody(bdef);

    PolygonShape s = new PolygonShape();
    s.setAsBox(50 / PPM, 5 / PPM);
    fdef.shape = s;
    b.createFixture(fdef);



    // Falling Box
    bdef.position.set(160 / PPM, 200 / PPM);
    bdef.type = BodyType.DynamicBody;
    Body b2 = world.createBody(bdef);

    PolygonShape s2 = new PolygonShape();
    s2.setAsBox(5 / PPM, 5 / PPM);
    fdef.shape = s2;
    fdef.restitution = .75f;
    b2.createFixture(fdef);

Now I attempt to put both fixtures on the Body b.

// create platform
    bdef.position.set(160 / PPM, 120 / PPM);
    bdef.type = BodyType.StaticBody;
    Body b = world.createBody(bdef);

    PolygonShape s = new PolygonShape();
    s.setAsBox(50 / PPM, 5 / PPM);
    fdef.shape = s;
    b.createFixture(fdef);



    // create falling box
    bdef.position.set(160 / PPM, 200 / PPM);
    bdef.type = BodyType.DynamicBody;
    //Body b2 = world.createBody(bdef);

    PolygonShape s2 = new PolygonShape();
    s2.setAsBox(5 / PPM, 5 / PPM);
    fdef.shape = s2;
    fdef.restitution = .75f;
    b.createFixture(fdef);

Barely any change here. Now that they’re on the same body, I attempt to move one up a bit by changing the y value but nothing happens. How would I make the small box move from inside the larger one?

EDIT: I can make it a circle-shape and change the fixture position, but how would I with another box?

Gdx.graphics.getDeltaTime(); Returns 0

$
0
0

I am coding a game in Java using Eclipse and Libgdx.

I am trying to make an object move until it reaches a certain random point. I am relying on delta time to make the objects speed the same on every device. But Gdx.graphics.getDeltaTime() is returning 0; so my game gets stuck in an infinite loop and the screen goes black. Gdx.graphics.getDeltaTime() returns a number greater than 0 in another one of my object classes.

package com.JrodManU.LaserJumper;

import java.util.Random;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.math.Rectangle;

public class Laser {
    public Sprite image;
    public Rectangle bounds;
    public LaserBeam laserBeam;
    public float targetY;
    Random random;

    public Laser(int x) {
        image = Assets.laser;
        random = new Random();
        bounds = new Rectangle(x, random.nextFloat() * (892 - 32) + 32, 32, 16);
        laserBeam = new LaserBeam();
    }

    public void fire() {
        targetY = random.nextFloat() * (892 - 32) + 32;
        if(bounds.y >= targetY) {
            while(bounds.y >= targetY) {
                bounds.y -= 6f * Gdx.graphics.getDeltaTime();
                System.out.println(bounds.y);
                System.out.println(Gdx.graphics.getDeltaTime());
            }
            bounds.y = targetY;
        } else {
            while(bounds.y < targetY) {
                bounds.y += 6f * Gdx.graphics.getDeltaTime();
                System.out.println(bounds.y);
                System.out.println(Gdx.graphics.getDeltaTime());
            }
            bounds.y = targetY;
        }
    }
}

Correctly identifying a Fixture from an extended class in Box2D's ContactListener

$
0
0

Sorry for the confusing title, I dont know how to resume it that much.

Im making a game, and I have a simple class Mob which is extended by Warrior and Enemy.

A Mob has a Body, and that body usually has one main Fixture.

Im setting the Body’s userdata to the class object (Warrior’s Body has a pointer to Warrior in its UserData) and im setting the Fixture’s userdata to a String which identifies what the fixture is. For example, the Warrior’s Body’s Fixture has the String “warrior” in its UserData.

The problem is, when a contact happens, i have common logic for a Mob, and i have specific logic for Warrior and Enemy.

Still, I cant find a good way to identify the collided fixtures at such a level.

For example, say I have these methods for code readability, since a Contact’s Fixture order is hard to guess and I dislike writing the same code for both Fixtures:

public boolean isPartOfContact(Contact c, String userdata)
{
    return (c.getFixtureA().getUserData().equals(userdata) ||
            c.getFixtureB().getUserData().equals(userdata));
}

public Fixture extractFixture(Contact c, String userdata)
{
    if(c.getFixtureA().getUserData().equals(userdata))
        return c.getFixtureA();

    if(c.getFixtureB().getUserData().equals(userdata))
        return c.getFixtureB();

    return null;
}

public Body extractBody(Contact c, String userdata)
{
    return extractFixture(c, userdata).getBody();
}

With these, I can write something like:

    if(isPartOfContact(contact, "warrior"))
    {
        if(isPartOfContact(contact, "map")) //warrior vs terrain
        {
            //Get warrior object
            ServerWarrior warrior = (ServerWarrior) extractBody(contact, "warrior").getUserData();
            //...
        }
    }

But what if I want to check for mob? warrior’s userdata is “warrior” and enemy’s userdata is “enemy”. Unless I check for class instances I cant think of a smart way of identifying them correctly.

I realise this really looks like fancy details which shouldnt really matter so soon in development but Im curious about how to create a Box2D ContactListener in a way which doesnt seem “hacked”.

Viewing all 434 articles
Browse latest View live