[英](libgdx) Why is my sprite being rendered so large?
我目前正在尝试学习 java 的 LibGDX 游戏引擎。 我使用的是平铺 map,每个平铺为 32*32 像素。 我还有一个大小为 48*64 的角色精灵。 在我的游戏中,我将 map 中的一个单元定义为一个图块。 出于某种原因,我的 map 渲染正确,但玩家精灵渲染异常大,而不是其预期的大约 2 个正方形单位的大小。
我试过在网上搜索类似的问题,但找不到像我的问题一样的东西。 我知道这与我正在使用的缩放比例有关,但我不知道解决它的好方法。
一种方法当然是在使用 batch.draw() function 绘制播放器精灵时简单地缩小播放器精灵,但我觉得这不是必需的。
@Override public void create () {
world = new World(new Vector2(0, -20), true); //Create Box2d world
debugRenderer = new Box2DDebugRenderer();
player1 = new Player();
camera = new OrthographicCamera(WORLD_WIDTH, WORLD_HEIGHT); //Create the camera I'm using, with width = height = 20
map = new TmxMapLoader().load("maps/Maptest.tmx"); //Load a map created in Tiled
this.mapObjects = map.getLayers().get(0).getObjects();
ObjectMapper.createShapes(this.mapObjects, this.world); //Load shapes from map for collision management
ObjectMapper.setSpawn(player1, mapObjects, world); //Set spawnpoint from object in the Tiled map
batch = new SpriteBatch();
renderer = new OrthogonalTiledMapRenderer(map, 1/PPT); //Create a tiled map renderer with unit scale 1/32
camera.update();
}
@Override
public void render () {
player1.update(); //Update player position
camera.position.set(player1.getX(), player1.getY(), 0); //Set position to players position
camera.update();
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
renderer.setView(camera); //Set renderer's view to camera view
renderer.render();
camera.update();
batch.setProjectionMatrix(camera.combined);
batch.begin();
batch.draw(player1.getSprite(), player1.getX()-player1.getSprite().getWidth()/2, player1.getY()-player1.getSprite().getHeight()/2); //Draw player sprite
batch.end();
System.out.println(player1.getX() + " " + player1.getY());
world.step(1/60f, 6, 2); //Iterate one step with Box2d world
debugRenderer.render(world, camera.combined); //Draw shapes
long javaHeap = Gdx.app.getJavaHeap();
long nativeHeap = Gdx.app.getNativeHeap();
}
@Override
public void resize (int width, int height) {
camera.viewportWidth = WORLD_WIDTH; // 20 units
camera.viewportHeight = (float)WORLD_HEIGHT*height/width;
camera.update();
}
我希望精灵的大小与半径为一个单位的玩家碰撞箱(圆形)大致相同。 相反,它变得非常大:
https://i.gyazo.com/6d814d10cd5f9bec322b601d538cb9ee.png
虽然完整的精灵看起来像这样:
https://i.gyazo.com/03178769d4a3b4beaba1612c76d37386.png
提前致谢:)
我会完全避免使用 Sprite class。 In LibGDX it was created as a highly optimized thing, but it conflates an asset (TextureRegion) with a game model object (a position and size, etc.), and violates the composition over inheritance guideline. 它还在 StackOverflow 上引起了许多问题,因为人们没有意识到它继承自 TextureRegion,但并不意味着通过将其传递给 SpriteBatch 来绘制(它并不意味着被视为 TextureRegion)。 要正确绘制它,您应该调用sprite.draw(batch)
,而不是batch.draw(sprite, ...)
。
您已经有一个播放器 class。 它应该只引用 TextureRegion 而不是 Sprite。 你可以给你的播放器 class 一个尺寸和 position(你实际想要的尺寸)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.