Flickering object image movement in libgdx desktop app

孤街醉人 提交于 2019-12-12 09:14:44

问题


This code makes image flicker while moving left,right,down or up.

public class MoveSpriteExample extends GdxTest implements InputProcessor  {
    Texture texture;
    SpriteBatch batch;
    OrthographicCamera camera;
    Vector3 spritePosition = new Vector3();
    Sprite sprite;

    public void create() {

        float w = Gdx.graphics.getWidth();
        float h = Gdx.graphics.getHeight();
        batch = new SpriteBatch();
        camera = new OrthographicCamera();
        camera.setToOrtho(false, w, h);

        texture = new Texture(Gdx.files.internal("data/TestImg.png"));

        texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
        sprite = new Sprite(texture);

        sprite.setSize(32, 32);
        spritePosition.y=100;

        sprite.setPosition(spritePosition.x,spritePosition.x);

    }

    public void render() {
        // set the clear color and clear the screen.
        Gdx.gl.glClearColor(1,1, 1, 1);
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
    //      camera.apply(Gdx.gl10);

        sprite.setPosition(spritePosition.x,spritePosition.y);


        batch.begin();
        sprite.draw(batch);
        batch.end();


        if (Gdx.input.isKeyPressed(Keys.D)==true)
        {
            spritePosition.x += 2;
        }else if (Gdx.input.isKeyPressed( Keys.A)==true)
        {
            spritePosition.x -= 2;
        }
        else if (Gdx.input.isKeyPressed( Keys.Z)==true)
        {
            spritePosition.y -= 2;
        }
        else if (Gdx.input.isKeyPressed( Keys.W)==true)
        {
            spritePosition.y += 2;
        }

        //  camera.unproject(spritePosition.set(Gdx.input.getX(), Gdx.input.getY(), 0));
        // if a finger is down, set the sprite's x/y coordinate.

    }
}

回答1:


Yes it does flicker because you move it 2px every frame. Thats like 120px in a second. You need to move it depending on the delta time. (and its always 2px at the time thats not smothy)

For example you want to move it 50px every second into the pressed direction you do it like this.

spritePosition.y += 50f*Gdx.graphics.getDeltaTime();

You do update everything depending on the deltatime not the framerate. The deltatime is the time between the last Frame and this frame.

Regular you would use a Screen to create a setup like this. If a screen is set the render method does get called with a delta time. (the method from the interface)

You should take a look at the steigert tutorial. It does give you a really great start with libgdx. Good luck with it.



来源:https://stackoverflow.com/questions/18959312/flickering-object-image-movement-in-libgdx-desktop-app

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!