LibGDX/Box2d - 只有一个矩形正在由debugrenderer渲染
问题描述:
我正在重新访问LibGDX游戏编程,我不幸要重新学习我以前知道的东西。LibGDX/Box2d - 只有一个矩形正在由debugrenderer渲染
我目前使用平铺地图编辑器来创建一个非常简单的金刚风格级别。我的水平总共有20个矩形。
我在我的主GameScreen类中创建了一个box2d世界,并有一个for循环让矩形对象进入世界和调试显示器。
我的问题是只有底部(和第一)矩形我画了出来。我已经检查了比例尺,我还放了一个println()
,它告诉我所有的矩形信息都显示正确(即矩形x,y,w,h值)的解析对象信息,但正如我所说,只有一个矩形显示在debugrenderer上。
我刚刚在6个月的休息时间后回到编程,所以我希望我错过了一些简单的事情。我的旧项目中的相同代码仍然正常工作,因为我测试了一些。
这是我的代码,任何帮助是大量赞赏。谢谢
public class GameScreen implements Screen {
SpriteBatch spriteBatch;
OrthographicCamera cam;
Viewport v;
TmxMapLoader mapLoader;
TiledMap map;
OrthogonalTiledMapRenderer mapRenderer;
World world;
Box2DDebugRenderer b2dr;
float mapScale = 10f/140f;
public GameScreen(){
spriteBatch = new SpriteBatch();
cam = new OrthographicCamera();
v = new FitViewport(Constants.V_WIDTH, Constants.V_HEIGHT, cam);
cam.setToOrtho(false, v.getWorldWidth(), v.getWorldHeight());
mapLoader = new TmxMapLoader();
map = mapLoader.load("level1.tmx");
mapRenderer = new OrthogonalTiledMapRenderer(map, mapScale);
world = new World(new Vector2(0,-9.8f), true);
b2dr = new Box2DDebugRenderer();
// box2d local variables
BodyDef bdef = new BodyDef();
PolygonShape shape = new PolygonShape();
FixtureDef fdef = new FixtureDef();
Body body;
// create platform object rectangles
for (MapObject object : map.getLayers().get(2).getObjects().getByType(RectangleMapObject.class)){
Rectangle rect = ((RectangleMapObject)object).getRectangle();
bdef.type = BodyDef.BodyType.StaticBody;
bdef.position.set(rect.getX() + rect.getWidth()/2 * mapScale, rect.y + rect.getHeight()/2 * mapScale);
body = world.createBody(bdef);
shape.setAsBox(rect.getWidth()/2 * mapScale, rect.getHeight()/2 * mapScale);
fdef.shape = shape;
body.createFixture(fdef);
}
}
@Override
public void show() {
}
@Override
public void render(float delta) {
update(delta);
clearScreen();
draw();
}
public void update(float dt){
mapRenderer.setView(cam);
}
public void clearScreen(){
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
public void draw(){
spriteBatch.setProjectionMatrix(cam.combined);
mapRenderer.render();
b2dr.render(world, cam.combined);
spriteBatch.begin();
spriteBatch.end();
}
@Override
public void resize(int width, int height) {
v.update(width, height);
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void hide() {
}
@Override
public void dispose() {
spriteBatch.dispose();
}
}
答
对不起在这里浪费时间。我解决了这个问题。
这只是我没有将地图的比例也应用到矩形的x,y。所以我改变了这样一条线,现在它的工作原理如下:
bdef.position.set(rect.getX() * mapScale + rect.getWidth()/2 * mapScale, rect.y * mapScale + rect.getHeight()/2 * mapScale);