如何在libgdx中正确使用setposition?

时间:2014-04-10 22:03:16

标签: libgdx

这是由v0.9.7的gdx-setup-ui.jar创建的java文件

sprite.setPosition(-sprite.getWidth()/2, -sprite.getHeight()/2);

为什么我们需要将位置设置为负值以使图像居中? libgdx图片的参考基点在哪里? (左下角?) 有人告诉我,libgdx的起源是左下角。鉴于上述值,部分图片应该在屏幕之外......事实证明不是!我很迷茫。 提前致谢

完整列表:

package com.packtpub.libgdx.basic;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;

public class Basic implements ApplicationListener {
    private OrthographicCamera camera;
    private SpriteBatch batch;
    private Texture texture;
    private Sprite sprite;

    @Override
    public void create() {      
        float w = Gdx.graphics.getWidth();
        float h = Gdx.graphics.getHeight();

        camera = new OrthographicCamera(1, h/w);
        batch = new SpriteBatch();

        texture = new Texture(Gdx.files.internal("data/libgdx.png"));
        texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);

        TextureRegion region = new TextureRegion(texture, 0, 0, 512, 275);

        sprite = new Sprite(region);
        sprite.setSize(0.9f, 0.9f * sprite.getHeight() / sprite.getWidth());
        sprite.setOrigin(sprite.getWidth()/2, sprite.getHeight()/2);
        sprite.setPosition(-sprite.getWidth()/2, -sprite.getHeight()/2);
    }

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

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

        batch.setProjectionMatrix(camera.combined);
        batch.begin();
        sprite.draw(batch);
        batch.end();
    }

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

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }
}

1 个答案:

答案 0 :(得分:2)

这是因为正交相机的默认中心点是(0,0,0),所以如果你只是在(0,0)处绘制图像,它的左下角短号将位于屏幕的中心。

您可以使用cam.position.set(w / 2,h / 2,0)方法更改此中心点

有关OrthographiCamera使用的详细示例,请参阅此处:https://github.com/libgdx/libgdx/wiki/Orthographic-camera