LibGDX中ShapeDrawer无渲染输出,仅显示黑屏问题求助
LibGDX ShapeDrawer 黑屏问题:无法渲染图形
使用LibGDX的ShapeDrawer组件时遇到问题,组件无法渲染任何图形,运行后仅显示黑屏。附上相关代码,寻求解决方法:
package com.davidclue.tanksii; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.PolygonSpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.utils.ScreenUtils; import com.davidclue.tanksii.input.InputHandler; import space.earlygrey.shapedrawer.ShapeDrawer; public class TanksII extends ApplicationAdapter { long lastTime = System.nanoTime(); double amountOfTicks = 60.0; double ns = 1000000000 / amountOfTicks; double delta = 0; long timer = System.currentTimeMillis(); int updates = 0; int frames; private PolygonSpriteBatch batch; private ShapeDrawer drawer; private TextureRegion region; public static int WIDTH = 1600, HEIGHT = 900; public int fullWidth, fullHeight; public static int tileSize = 64; public String title = "Tanks II"; public static Handler handler; private Level level; @Override public void create() { batch = new PolygonSpriteBatch(); region = new TextureRegion(new Texture(WIDTH, HEIGHT, Format.RGBA8888)); drawer = new ShapeDrawer(batch, region); handler = new Handler(); new Camera(0, 0); new InputHandler(this); level = new Level(this, handler); handler.setLevel(level); level.load("levels/default/level1.png"); } private void tick() { handler.tick(); Camera.tick(); } @Override public void render() { long now = System.nanoTime(); delta += (now - lastTime) / ns; lastTime = now; while (delta >= 1) { tick(); updates++; delta--; } if (System.currentTimeMillis() - timer > 1000) { timer += 1000; System.out.println("FPS: " + frames + " TICKS: " + updates); frames = 0; updates = 0; } // render ScreenUtils.clear(0, 0, 0, 1); batch.begin(); level.render(drawer); handler.render(drawer); drawer.filledRectangle(10, 10, 100, 100, Color.CYAN); batch.end(); frames++; } @Override public void dispose() { batch.dispose(); } }
问题解决要点
修复ShapeDrawer的纹理画笔
当前用空纹理初始化TextureRegion,ShapeDrawer无法正常绘制。替换成1x1的白色纹理:@Override public void create() { batch = new PolygonSpriteBatch(); // 创建1x1白色纹理作为ShapeDrawer的画笔 Pixmap pixmap = new Pixmap(1, 1, Pixmap.Format.RGBA8888); pixmap.setColor(Color.WHITE); pixmap.fill(); region = new TextureRegion(new Texture(pixmap)); pixmap.dispose(); // 释放Pixmap资源 drawer = new ShapeDrawer(batch, region); // 其他初始化代码... }应用相机投影矩阵
创建Camera后未将其矩阵绑定到Batch,导致绘制内容不在视口内。在batch.begin()前添加:ScreenUtils.clear(0, 0, 0, 1); // 假设Camera类中有OrthographicCamera实例名为camera batch.setProjectionMatrix(Camera.camera.combined); batch.begin();补全资源释放
在dispose方法中添加纹理的释放,避免内存泄漏:@Override public void dispose() { batch.dispose(); region.getTexture().dispose(); }
内容的提问来源于stack exchange,提问作者JewishBanana
相关产品推荐
相关产品推荐

