1
\$\begingroup\$

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 :)

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

TextureRegions have their own width and height properties, as they are subimages of a full Texture. If you want to center your animation for each frame, you're going to have to use the height and width from each frame when rendering

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

    elapsedTime += Gdx.graphics.getDeltaTime();
    TextureRegion frame = animation.getKeyFrame(elapsedTime, true)
    batch.begin();
    batch.draw(frame, -frame.getRegionWidth()/2f, -frame.getRegionHeight()/2f);
    batch.end();
}

These values have no need to be stored in a higher scope than the render method.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .