当我尝试使用SpriteBatch绘制纹理时,结果是这样的翻转:
这是我的工作:
我创建MyRect对象,该对象绘制边界矩形和图像.
这里是MyRect类的预览:
public class MyRect {
private Vector2 position;
private int width;
private float height;
private Texture img;
private Sprite sprite;
public MyRect(int x, int y, int width, int height){
img = new Texture("badlogic.jpg");
sprite = new Sprite(img);
position = new Vector2(x,y);
this.width = width;
this.height = height;
}
public void draw(ShapeRenderer shapeRenderer, SpriteBatch batch){
// Gdx.gl.glClearColor(0, 0, 0, 1);
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
shapeRenderer.begin(ShapeType.Line);
// Draw Background color
shapeRenderer.setColor(55 / 255.0f, 80 / 255.0f, 100 / 255.0f, 1);
shapeRenderer.rect(position.x, position.y, width, height);
shapeRenderer.end();
batch.begin();
// batch.disableBlending();
batch.draw(img, position.x, position.y,
width, height);
batch.end();
}
}
参数ShapeRenderer和SpriteBatch通过GameScreen类传递.
GameScreen预览:
public class GameScreen implements Screen{
private MyRect myRect;
private ShapeRenderer shapeRenderer;
private SpriteBatch batch;
private OrthographicCamera cam;
public GameScreen(){
myRect = new MyRect(10,10,50,50);
int gameHeight=100;
cam = new OrthographicCamera();
cam.setToOrtho(true, 136, gameHeight);
batch = new SpriteBatch();
batch.setProjectionMatrix(cam.combined);
shapeRenderer = new ShapeRenderer();
shapeRenderer.setProjectionMatrix(cam.combined);
}
@Override
public void render(float delta) {
// Todo Auto-generated method stub
myRect.draw(shapeRenderer, batch);
}
}
为什么会这样呢?我做错了吗?
解决方法:
您的相机颠倒了,因为您在其上调用了setToOrtho(true,…)而不是setToOrtho(false,…)
使用倒置摄像头是有效的(如果以前使用过Flash或其他Y倒置系统,可能会更舒适),但随后需要翻转所有TextureRegions(又名Sprites):sprite.flip(错误,正确).另外,您可以使用TexturePacker创建一个TextureAtlas(在libgdx文档中查找)并设置flipY选项,以便它为您提前翻转它们.最终,为了提高性能,您仍然需要使用TextureAtlas.
顺便说一句,当您开始绘制MyRect的多个实例时,您需要将spriteBatch.begin()和end()以及shapeRenderer.begin()和end()从单个MyRect的draw方法中移出,否则您将遇到性能问题.因此,将需要两种绘制方法(一种用于精灵批处理,一种用于形状渲染器).