1
votes

I'm having problems to centralize my sprite animation can someone please give me a light?

public void render() {
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

    stateTime += Gdx.graphics.getDeltaTime();                       
    currentFrame = walkAnimation.getKeyFrame(stateTime, true);      



    batch.setProjectionMatrix(cam.combined);
    batch.begin();
    batch.draw(currentFrame, Gdx.graphics.getWidth() / 2 - ((walkSheet.getWidth()/FRAME_COLS) / 2), Gdx.graphics.getHeight() / 2 - ((walkSheet.getHeight()/FRAME_ROWS) / 2), width / 2, height / 4);                          

My animation is being draw a few pixels to the left.

1
It looks like you're trying to compute the current frame's width with walkSheet.getWidth()/FRAME_COLS...why not just call currentFrame.getWidth() instead? - DannyMo
@damo Thanks for the answer, but it just gave me the same results, when running on desktop the animation gets draw a bit to the right and when running on my phone it's a bit to the left, maybe is not that piece of code that I must change? - Ivan Carlos
I would also make sure that you defined your TextureRegions correctly. The TextureRegion might be centered on the screen, but the sprite might not be centered within the TextureRegion. - DannyMo

1 Answers

1
votes

For x position, you have-

Gdx.graphics.getWidth() / 2 - ((walkSheet.getWidth()/FRAME_COLS) / 2)

If each animation image is 100px wide, why don't you use-

private static final float WALK_ANIM_WIDTH = 100f;

X position would be then -

Gdx.graphics.getWidth() / 2f - WALK_ANIM_WIDTH / 2f

UPDATE:

Based from your comment, you can have something like-

public static final int SCREEN_WIDTH = 800;
public static final int SCREEN_HEIGHT = 520;

guiCam = new OrthographicCamera(SCREEN_WIDTH, SCREEN_HEIGHT);
guiCam.position.set(SCREEN_WIDTH / 2f, SCREEN_HEIGHT / 2f, 0);

Now rather than using "Gdx.graphics.getWidth()", you can simply use SCREEN_WIDTH.

Take a look at the SuperJumper demo in libGDX. You will see how they used the viewport in game world.