简体   繁体   中英

Centering an animation [libGDX]

I have the following class:

public class AnimationDemo implements ApplicationListener {
    private SpriteBatch batch;
    private TextureAtlas textureAtlas;
    private Animation animation;
    private float elapsedTime = 0;
    private OrthographicCamera camera;
    private int width;
    private int height;
    private int texturewidth;
    private int textureheight;

    @Override
    public void create() {
        width = Gdx.graphics.getWidth();
        height = Gdx.graphics.getHeight();
        camera = new OrthographicCamera(width, height);
        camera.position.set(width / 2, height / 2, 0);
        camera.update();


        batch = new SpriteBatch();
        textureAtlas = new TextureAtlas(Gdx.files.internal("data/packone.atlas"));


        textureAtlas.getRegions().sort(new Comparator<TextureAtlas.AtlasRegion>() {
            @Override
            public int compare(TextureAtlas.AtlasRegion o1, TextureAtlas.AtlasRegion o2) {
                return Integer.parseInt(o1.name) > Integer.parseInt(o2.name) ? 1 : -1;
            }
        });

        animation = new Animation(1 / 15f, textureAtlas.getRegions());

    }

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

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

        batch.begin();
        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() {
    }
}

In the above I am using the Animation class to simply draw from a texture atlas. I am following an example from another SO question which is here but the co-ordinates don't fit my equation. How should I set these:

private int texturewidth;
private int textureheight;

Any help would be great :)

you need to care about proper offset - the origin is always at the left bottom corner and that is why you need to subtract half of width and height when drawing.

In a nutshell it should be like:

    TextureRegion region = animation.getKeyFrame(elapsedTime, true);
    batch.draw(region, 0 - (region.getRegionWidth()/2f), 0 - (region.getRegionHeight()/2f));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM