[英](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.