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

How can I implement a camera like the one in RotMG?

$
0
0

RotMG, an MMO top-down shooter, takes on a unique 2d-3d style, and has an intriguing camera;
enter image description here

The game is obviously 3d, not simply isometric, and if you play the game and turn on camera rotation you will notice the effect the game produces, like so.

RotMG is made using flash, and I am currently experimenting with libgdx (which uses lwjgl/opengl). How should I go about implementing a RotMG-like camera?


how can I split the screen into two screens and make Gdx.input.setInputProcessor () accept two processors?

$
0
0

I want to draw in the first screen portion, and manipulate the buttons in the second part.

This is what I tried:

if (mouse.x <600) {
Gdx.input.setInputProcessor (new InputProcessor () {

Override
public boolean touchup (int arg0, int arg1, int arg2, int arg3) {
return false;
}
.
.
.
.
.
}
if (mouse.x> = 600) {
Gdx.input.setInputProcessor (stage);
}

the problem is that I have the ability to go from the first part to the second but I’m not allowed to go from the second to the first, it blocks the mouse coordinates in x = 600 This is what I tried

FPS drop after moved from Textures to TextureAtlas in LibGDX

$
0
0

I’ve started using LibGDX some time ago and I was making a test project to get used to this library. I’ve created some images and added them to the assets folder and loaded each image as a Texture using the AssetManager. Everything was working fine and I had 60 FPS.

I wanted to work in a more efficient way so I packed all my images into an atlas using the TexturePacker tool. I loaded the atlas using the AssetManager again and started using TextureRegions instead of Textures.

After this change I’ve started to notice sudden drops in FPS from 60 to 50 and even 30 once. I’ve tried to change the pixel format to RGBA4444, I’ve made sure that the min and mag filter were both seth to Nearest, but still I see those annoying frame drops.

I’m not doing anything heavy in the game itself, it’s currently some actors in a stage. I got some MoveActions and Animation, but nothing special yet.

Does anyone have a clue what can cause the FPS drop?

Thanks

Placeing stones/tiles on a board game

$
0
0

I am a beginner at libGdx.

I am building a board game (the Fanorama game). I would like to use a pic as the board and place the pieces on the board on top of the board sprite. Is there a nice way to pre-determine what (x,y) co-ordinate locations on the board sprite are valid for placing a piece. Later on, when the game is being played I would like to move the pieces from location to location.

Right now, the only way I can think of is to calculate each piece location pixel co-ordinates and hard-code it in an array. I am not sure if there is a better way to do this and a best practice way for me to learn. I am also concerned if this will be affected when the user resized the screen or uses a different sized device (mobile).

How to solve this problem?

Is there a Box2d b2World::ShiftOrigin function in Libgdx?

$
0
0

Is there an equivalent Box2d b2World::ShiftOrigin function in Libgdx? I can’t seem to find it.

LibGDX Box2D TileGame Efficiency

$
0
0

I am trying to implement Box2D into my top down tile game in LibGDX. Each world consists of a set of chunks, and each chunk is 16 tiles wide/long. The maximum/minimum chunks loaded at one time is 9 (a 3×3 set of chunks with the player in the middle). This means that there are 2304 tiles active at all times.

I have tried creating a Static box shape for each of these tiles but performance was understandably terrible. I then tried creating a box shape for each of these tiles that are solid. Performance was still terrible because at one time there was 500-1000 individual boxes.

One partial solution I found to this is reducing the chunk size. At chunk size 8 with boxes around only solid tiles performance was 60 fps on mobile devices, however this was only sustained when the chunks that were loaded did not contain many solid tiles so this isn’t really a solution.

I then came across a potential solution which would join all solid adjacent tiles within a chunk, so that instead of having a box for each individual solid tile, there would be a irregular polygon for each set of connected solid tiles. This solution appears to be the best, however what would happen when I want to destroy a solid tile. I would then have to recalculate all of the tile connections within that chunk and recreate another irregular polygon. To get around this, I then thought of dividing the chunk up into 4×4 sections. Each of these sections would handle their own irregular polygon so that when a tile was destroyed only that section would need to be updated and recalcuated. This however increases the number of bodies in the box2d world compared to the previous solution where there is just 1 body for each group of solid tiles.

I am looking for any other ideas that might help.

On a side note: The only reason I am using box2D is so I can achieve a nice lighting effect with shadows and everything with box2DLights. If there are any substitutes of this library that you know of please let me know!

How to properly change resolution

$
0
0

I’m trying to understand how LibGDX handles screen size / resolution, etc.
Coming from XNA this seems very confusing to me. Basically I want to support 480×800 for my game. If the screen size is different it should scale the resolution and use letterboxing. To do this I use a FitViewport. And that’s the code:

public static final int VIRTUAL_WIDTH = 480;
public static final int VIRTUAL_HEIGHT = 800;
Viewport viewport;
SpriteBatch spriteBatch;
ShapeRenderer shapeBatch;
Texture img;

@Override
public void create()
{
    viewport = new FitViewport(VIRTUAL_WIDTH, VIRTUAL_HEIGHT);
    spriteBatch = new SpriteBatch();
    shapeBatch = new ShapeRenderer();
    img = new Texture("test.jpg");
}

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

@Override
public void render()
{
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    shapeBatch.begin(ShapeType.Filled);
    shapeBatch.setColor(Color.GRAY);
    shapeBatch.rect(0, 0, viewport.getWorldWidth(), viewport.getWorldHeight());
    shapeBatch.end();

    spriteBatch.begin();
    spriteBatch.draw(img, 0, 0);
    spriteBatch.end();
}

Now if I set the game resolution to be 480×800 right at the beginning, it basically works except that if I change the window size, the resolution keeps to be 480×800. So it stretches the image but keeps the aspect ratio:
screen1

And if I run the game with any other resolution like for example 700×500 I get this:
screen2

What is going on behind the scenes?
(And sorry if my english is bad)

LibGDX: Its there any way to calculate the speed of a repeated scrolling background?

$
0
0

I’m trying to calculate the scrolling speed of an background, I’m doing something like this on the background class:

private Texture texture = new Texture(Gdx.files.internal("backgound.png"));
private Sprite sprite;

private float scrollTimer = 0.0f;
private static float scrollFactor = 0.2f;


public Background() {
    texture.setWrap(TextureWrap.Repeat, TextureWrap.Repeat);
    int width = texture.getWidth();
    int height = texture.getHeight();
    sprite = new Sprite(texture, 0, 0, width, height);
    sprite.setSize(1280, 320);

}

@Override
public void act(float delta) {
    updateScrollFactor();
    scrollTimer += delta * scrollFactor;

    if (scrollTimer > 1.0f) {
        scrollTimer = 0.0f;
    }

    sprite.setU(scrollTimer);
    sprite.setU2(scrollTimer + 2);
}

@Override
public void draw(Batch batch, float alpha) {
    sprite.draw(batch, alpha);
}

private void updateScrollFactor() {
    //Increase scroll factor when the game score being higher.
}

public static float getScrollFactor() {
    return scrollFactor;
}

And in another class I’m trying to calculate the speed of this background above because I need the same speed to apply in the entity of mentioned class, that is described below:

private Texture texture;
private Sprite sprite;

public Item(String textureName) {
    texture = new Texture(Gdx.files.internal(textureName));
    int width = texture.getWidth();
    int height = texture.getHeight();
    sprite = new Sprite(texture, 0, 0, width, height);
    sprite.setSize(30f, 50f);
    //Sets initial position, the entity will be scrolled from the screen width to zero  
    sprite.setPosition(Gdx.app.getWidth() - 10, 10);
}

@Override
public void act(float delta) {
    scrollTimer = delta * Background.getScrollFactor();

    if (scrollTimer > 1.0f) {
        scrollTimer = 0.0f;
    }

    float x = sprite.getX();
    if (x + sprite.getWidth() > 0) {
        sprite.setX(x - Gdx.graphics.getWidth() * scrollTimer);
    } else {
        //sets to initial position when the entity vanish thru the window left side.
        sprite.setX(Gdx.graphics.getWidth() - 10);
    }
}

@Override
public void draw(Batch batch, float alpha) {
    sprite.draw(batch, alpha);
}

}

The case is the entity don’t run sync with background but i need this separated from the background because it is a clickable entity.

Thoughts?


LibGdx Exception

$
0
0

Here is the exception:

Exception in thread "LWJGL Application" java.lang.NullPointerException
at com.mygdx.test.excav.game.WorldRender.renderTest(WorldRender.java:34)
at com.mygdx.test.excav.game.WorldRender.render(WorldRender.java:28)
at com.mygdx.test.excav.MainGame.render(MainGame.java:41)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:207)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:114)

Relevant Code:

public class MainGame extends ApplicationAdapter {

    private static final String TAG = MainGame.class.getName();
    private WorldInit worldInit;
    private WorldRender worldRender;
    private boolean paused;

    @Override
    public void create () {

        Gdx.app.setLogLevel(Application.LOG_DEBUG);

        worldInit = new WorldInit();
        worldRender = new WorldRender(worldInit);

        paused = false;
    }

    @Override
    public void render () {
        if (!paused) {
            worldInit.update(Gdx.graphics.getDeltaTime());
        }
        Gdx.gl.glClearColor(0x64/255.0f, 0x95/255.0f, 0xed/255.0f, 0xff/255.0f);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        worldRender.render();
    }

    @Override
    public void resize (int width, int height) {
        worldRender.resize(width, height);
    }

    @Override
    public void pause () {
        paused = true;
    }

    @Override
    public void resume () {
        paused = false;
    }

    @Override
    public void dispose () {
        worldRender.dispose();
    }
}

public class WorldInit {
    private static final String TAG = WorldInit.class.getName();
    public Sprite[] testSprites;
    public int curSprite;

    public WorldInit () {
        init();
    }

    private void init () {
        initTest();
    }

    private void initTest() {
        testSprites = new Sprite[5];

        int width = 32;
        int height = 32;

        Pixmap pixmap = createPixmap(width, height);
        Texture texture = new Texture(pixmap);

        for (int i = 0; i < testSprites.length; i++) {
            Sprite spr = new Sprite(texture);
            spr.setSize(1, 1);
            spr.setOrigin(spr.getWidth() / 2.0f, spr.getHeight() / 2.0f);
            // Calculate random position for sprite
            float randomX = MathUtils.random(-2.0f, 2.0f);
            float randomY = MathUtils.random(-2.0f, 2.0f);
            spr.setPosition(randomX, randomY);
            // Put new sprite into array
            testSprites[i] = spr;
        }
        // Set first sprite as selected one
        curSprite = 0;
    }

    private Pixmap createPixmap(int width, int height) {
        Pixmap pixmap = new Pixmap(width, height, Format.RGBA8888);
        pixmap.setColor(1, 0, 0, .5f);
        pixmap.fill();
        pixmap.setColor(1, 1, 0, 1);
        pixmap.drawLine(0, 0, width, height);
        pixmap.drawLine(width, 0, 0, height);
        pixmap.setColor(0, 1, 1, 1);
        pixmap.drawRectangle(0, 0, width, height);
        return pixmap;
    }

    public void update (float deltaTime) {
        updateTest(deltaTime);
    }

    private void updateTest(float deltaTime) {
        float rotation = testSprites[curSprite].getRotation();
        rotation += 90 * deltaTime;
        rotation %= 360;
        testSprites[curSprite].setRotation(rotation);
    }
}

public class WorldRender implements Disposable {
    private OrthographicCamera camera;
    private SpriteBatch batch;
    private WorldInit worldInit;

    public WorldRender(WorldInit worldinit) {
        this.worldInit = worldInit;
        init();
    }

    private void init() {
        batch = new SpriteBatch();
        camera = new OrthographicCamera(Constant.VIEWPORT_WIDTH,
        Constant.VIEWPORT_HEIGHT);
        camera.position.set(0, 0, 0);
        camera.update();
    }

    public void render() {
        renderTest();   
    }

    private void renderTest() {
        batch.setProjectionMatrix(camera.combined);
        batch.begin();
        for(Sprite sprite : worldInit.testSprites) {
            sprite.draw(batch);
        }
        batch.end();
    }

    public void resize(int width, int height) {
        camera.viewportWidth = (Constant.VIEWPORT_HEIGHT / height) *
        width;
        camera.update();
    }

    @Override
    public void dispose() {
        batch.dispose();
    }
}

How do I make a pop-up window with Scene2D?

$
0
0

I have a main-menu screen with a logo and a bunch of buttons. When the Login-button is pressed, I pop up a dialogue asking for a username and password.

This works fine, other than the “popping up”. At the moment the new the dialogue box just shifts everything about, but I’d want to position it over the current scene.

I’m just learning Scene2D.

Creating a glitch effect similar to Watch Dogs

$
0
0

I’m currently working on a LibGDX game. When a user does something wrong, I would like all the graphics on the screen to jitter very similar to the glitch/distort effect seen in the game Watch Dogs (See Below).

My question is this: can this effect be achieved in real time by writing a shader? If so are there any references online on how to do this? (I’ve had a quick Google but all I could find is how to achieve this effect in Photoshop/After Effects).

Thank you for your help.

Screen jitter: https://www.youtube.com/watch?v=EYkqC9uI8Nc

Text glitch effect: https://www.youtube.com/watch?v=Wj26Wp2AH-U

enter image description here

(LibGdx) Get mouse position in ENTIRE game [closed]

$
0
0

I’m trying to get the mouse position IN GAME. By that I mean not the position on the screen, but inside the window. I’ve been using Gdx.input.getX(), but that’s not INGAME. How do I do this?

Box2D – create object with different physic parts

$
0
0

I have object with physic:

    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyDef.BodyType.DynamicBody;
    bodyDef.position.set(position);
    bodyDef.angle = angle;
    this.body = world.createBody(bodyDef);

    //init shape
    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.density = 1.0f;
    fixtureDef.friction = 0.6f; 
    fixtureDef.restitution  = 2.94f; 
    fixtureDef.isSensor = false;
    PolygonShape carShape = new PolygonShape();
    carShape.setAsBox(this.width / 2, this.length / 2);

    fixtureDef.shape = carShape;
    this.body.createFixture(fixtureDef); `
    addWheels(..);

There is defined carShape like rectangle with physic. Next code is adding wheels. I want add to the center of car another shape or line, which won’t have affect to physic of car and without physic – only rendered but moving with the car. Visible for information purposes only. What is the easiest option to make it?

For example red line:
enter image description here

Event handling for Pressing only 4 keys on desktop

$
0
0

I want to poll only 4 keys i.e. Keys.LEFT, Keys.RIGHT, Keys.Up and Keys.Down in libGDX strictly.
That means, I want to call render method, only when above 4 keys are pressed.

I followed below link and implemented InputProcessor (see code below), extending InputAdapter for keyDown only.

https://github.com/libgdx/libgdx/wiki/Event-handling

Gdx.input.setInputProcessor(new InputAdapter () {
            @Override
               public boolean keyDown (int keycode) {
                if(keycode==Keys.LEFT)
                {
                    System.out.println("left");
                    }
                if(keycode==Keys.RIGHT)
                {
                    System.out.println("right");
                }
                if(keycode==Keys.DOWN)
                {
                    System.out.println("DOWN");
                }
                if(keycode==Keys.UP)
                {
                    System.out.println("UP");
                }
                return true;
               }    
        });

But i am not getting the result as expected.

After running application on desktop, whenever I move mouse pointer over game screen or pressing other keys , its FPS is changing . That means render method is being called. Why?

Here is my full code for testing. See the output at bottom.

package com.GDXTests.game;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.FPSLogger;

public class FPSTest extends ApplicationAdapter {
    private Texture tex;
    private SpriteBatch batch;
    private OrthographicCamera camera;
    public FPSLogger fpslog;

    @Override
    public void create ()
    {
    // Loading Texture
         tex=new Texture(Gdx.files.external("desktop/bit0.jpg"));
         camera = new OrthographicCamera();
         camera.setToOrtho(false, 256, 256);
         batch = new SpriteBatch();
          //initializing logger
         fpslog=new FPSLogger();
          //disabling the continuous rendering
         Gdx.graphics.setContinuousRendering(false);
         Gdx.graphics.requestRendering();
    }
    @Override
    public void render () {

        //logging fps
        fpslog.log();
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
         // tell the camera to update its matrices.
          camera.update();
          // tell the SpriteBatch to render in the
          // coordinate system specified by the camera.
          batch.setProjectionMatrix(camera.combined);

        batch.begin();
        batch.draw(tex,2,3);
        batch.end();

        Gdx.input.setInputProcessor(new InputAdapter () {
            @Override
               public boolean keyDown (int keycode) {
                if(keycode==Keys.LEFT)
                {
                    System.out.println("left");
                }
                if(keycode==Keys.RIGHT)
                {
                    System.out.println("right");
                }
                if(keycode==Keys.DOWN)
                {
                    System.out.println("DOWN");
                }
                if(keycode==Keys.UP)
                {
                    System.out.println("UP");
                }
                return true;
               }        
        });
    }
     @Override
       public void dispose() {
          // dispose of all the native resources
         tex.dispose();   
         batch.dispose();
       }
       @Override
       public void resize(int width, int height) {
       }
       @Override
       public void pause() {
       }
       @Override
       public void resume() {
       }
}

Here is the output of logger:

right
FPSLogger: fps: 2
left
UP
FPSLogger: fps: 5
DOWN
left
FPSLogger: fps: 3
right
UP
DOWN
FPSLogger: fps: 6       // move mouse pointer over screen, not pressing any keys
FPSLogger: fps: 2       // move mouse pointer over screen, not pressing any keys
FPSLogger: fps: 61      // move mouse pointer over screen, not pressing any keys
FPSLogger: fps: 24      // move mouse pointer over screen, not pressing any keys
FPSLogger: fps: 52      // move mouse pointer over screen, not pressing any keys
FPSLogger: fps: 14      // move mouse pointer over screen, not pressing any keys
FPSLogger: fps: 21      // move mouse pointer over screen, not pressing any keys
UP
FPSLogger: fps: 15
DOWN
FPSLogger: fps: 2
left
right
FPSLogger: fps: 4
right
FPSLogger: fps: 3
right
FPSLogger: fps: 3

I want something like this

right
FPSLogger: fps: 1
left
FPSLogger: fps: 1
DOWN
FPSLogger: fps: 1
UP
FPSLogger: fps: 1

Thanks in Advance!

how to remove game objects after on overlap in LIBGDX game

$
0
0

I have gold stars in my game that give score to game hero if the hero overlap with the star. What I want is to remove star once it overlap with hero object.
I give score by checking overlap with this code

public void scorecount(Hero myhero){

            if (!star.isScored() && Intersector.overlaps(myhero.getBoundingBalloon(), star.getStarCircle())) 
    {

                addScore(1); // give one plus always
  star.setScored(true);


AssetLoader.coin.play();

}

Now once I give score and setScore true , i want to remove star.
How can I do that?
I tried for setvisible method but I dont know how to use it. Because just Calling star.setVisible() ask to create this method in star class. then in star class I dont know what should be given inside this method body.


Using SVN with Libgdx

$
0
0

I decided to give LibGDX a try and am planning to use SVN for my code repository. I created my LibGDX project via the Gradle build as outlined in the book “Learning LibGDX Game Development”. I’m not quite sure how to add the project to my repository. I have tried to upload the root folder (Project below) into svn, which does contain all the sub-project, but when I check out my workspace only contains the Project folder.

Below is the structure of the project in Eclipse after the gradle build.

  1. Project
  2. Project-android
  3. Project-core
  4. Project-desktop
  5. Project-html
  6. Project-ios

After checking out from svn

  1. Project

Has anyone used SVN with LibGDX, if yes can you please guide on how to add a project to repo and checkout correctly?

Generating 3D-like effect

$
0
0

I’m making a 2D sidescroller game and want to give the blocks a 3D like effect. This way it looks like the player is walking on 3D blocks while walking on a 2D plane (thus having only x,y coordinates).

I have already written the code to generate the terrain in 2D, but the 3D effect is now baked in. It looks like this:enter image description here

At this moment the 3D effect is baked into the blocks, but I want to try to generate it.

Is there a common way to achieve this 3D like effect while still staying 2D?
Do I have to convert from 2D to 3D or is it also possible to do this with calculations/shaders?

EDIT; The reason I want the top texture of the block separate of the block is because when the camera would go up, the top should get bigger as the camera sees more of the top of the block and the other way around when the camera goes down.

Help Understanding libgdx create animations example game

$
0
0

I am trying to understand the example game, cuboc. GitHub is https://github.com/libgdx/libgdx-demo-cuboc. I have generated my texture atlas but I do not understand the code that uses this texture atlas. Here’s the code (you can see on github too here:

package com.badlogic.cubocy;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.FPSLogger;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.SpriteCache;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.glutils.ImmediateModeRenderer20;
import com.badlogic.gdx.math.Vector3;

public class MapRenderer {
...
    private void createAnimations () {
        this.tile = new TextureRegion(new Texture(Gdx.files.internal("data/tile.png")), 0, 0, 20, 20);
        Texture bobTexture = new Texture(Gdx.files.internal("data/bob.png"));
        TextureRegion[] split = new TextureRegion(bobTexture).split(20, 20)[0];
        TextureRegion[] mirror = new TextureRegion(bobTexture).split(20, 20)[0];
        for (TextureRegion region : mirror)
            region.flip(true, false);
        spikes = split[5];
        bobRight = new Animation(0.1f, split[0], split[1]);
        bobLeft = new Animation(0.1f, mirror[0], mirror[1]);
        bobJumpRight = new Animation(0.1f, split[2], split[3]);
        bobJumpLeft = new Animation(0.1f, mirror[2], mirror[3]);
        bobIdleRight = new Animation(0.5f, split[0], split[4]);
        bobIdleLeft = new Animation(0.5f, mirror[0], mirror[4]);
        bobDead = new Animation(0.2f, split[0]);
        split = new TextureRegion(bobTexture).split(20, 20)[1];
        cube = split[0];
        cubeFixed = new Animation(1, split[1], split[2], split[3], split[4], split[5]);
        split = new TextureRegion(bobTexture).split(20, 20)[2];
        cubeControlled = split[0];
        spawn = new Animation(0.1f, split[4], split[3], split[2], split[1]);
        dying = new Animation(0.1f, split[1], split[2], split[3], split[4]);
        dispenser = split[5];
        split = new TextureRegion(bobTexture).split(20, 20)[3];
        rocket = new Animation(0.1f, split[0], split[1], split[2], split[3]);
        rocketPad = split[4];
        split = new TextureRegion(bobTexture).split(20, 20)[4];
        rocketExplosion = new Animation(0.1f, split[0], split[1], split[2], split[3], split[4], split[4]);
        split = new TextureRegion(bobTexture).split(20, 20)[5];
        endDoor = split[2];
        movingSpikes = split[0];
        laser = split[1];
    }

What I do not understand is what is split used for? Like, what is going on here:

split = new TextureRegion(bobTexture).split(20, 20)[1];

And sometimes it looks like split is a method that takes two int‘s, 20 and 20? Why 20?
Othertimes split is used as an Array like in …

rocketExplosion = new Animation(0.1f, split[0], split[1], split[2], split[3], split[4], split[4]);

… and I just can’t follow what’s going on here. Thanks!

Box2D body rotation with setTransform

$
0
0

I’ having a problem rotating a body with setTransform(), The body has multiple sensors that should rotate with the player. The rotation works but it rotates around the bodys local 0,0 position instead of the center. Note that the game is in a top-down perspective and the player can go in four different directions, thus I need to rotate him immediately (in one tick) in 90 degrees steps.

Up:

enter image description here

Down:

enter image description here

I can’t find a way to set the rotation center.

Here’s the code I use to rotate it:

float angle = direction * 90 * MathUtils.degRad; // direction is an int value from 0 to 3
body.setTransform(body.getPosition(), angle);

I also tried body.getLocalCenter().set() and body.getMassData().center.set() but it didn’t seem to have any effect. How can I rotate the body around its center?

EDIT (added code to create fixtures):

This is the method to create a fixture:

private Fixture createFixture(FixtureDef fixtureDef, Body body) {
    PolygonShape ps = createPolygon(); // creates a polygon shape from XML config
    fixtureDef.shape = ps;
    Fixture fixture = body.createFixture(fixtureDef);

    if (fc.filter != null) {
        fixture.setFilterData(fc.filter);
    }
}

This is the simplified code to create the fixtures (they are really loaded with xml config but these are the values I set):

FixtureDef sensorDef1 = new FixtureDef();
sensorDef1.friction = 0;
sensorDef1.restitution = 0;
sensorDef1.isSensor = true;
sensorDef1.center = new Vector2(0.8f, 1.6f);
// and some filters

FixtureDef sensorDef2 = new FixtureDef();
sensorDef2.isSensor = true;
sensorDef2.center = new Vector2(0.8f, 1.6f);
// and some filters

FixtureDef sensorDef3 = new FixtureDef();
sensorDef3.isSensor = true;
// and some filters

createFixture(sensorDef1, body);
createFixture(sensorDef2, body);
createFixture(sensorDef3, body);

How to increase the acceleration of an object on the Y axis? [duplicate]

Viewing all 434 articles
Browse latest View live