我最近刚刚开始使用 libGDX 来制作游戏,并且我正在尝试实现一个正交相机,以便在玩家移动时让玩家放松(制作 2D 横向卷轴)。由于某种原因,我不明白当我执行所有应该使相机将玩家绘制在屏幕中心的操作时,玩家会稍微向右上角移动。
我一整天都在尝试不同的事情,但没有找到任何解决方案。
如果它有帮助的话,我的玩家 Sprite 是一个方形的 128 x 128 图像,我的显示器尺寸是 1366x768
这是我的游戏屏幕代码:
package com.inertiafall.inertiaengine.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Vector3;
import com.inertiafall.inertiaengine.InertiaEngine;
import com.inertiafall.inertiaengine.InputHandler;
import com.inertiafall.inertiaengine.entities.Player;
public class GameScreen implements Screen {
InertiaEngine game;
SpriteBatch batch;
Player player;
OrthographicCamera cam;
float width, height;
ShapeRenderer sr;
public GameScreen(InertiaEngine game){
this.game = game;
}
public void show() {
player = new Player(5, 5);
player.init();
width = Gdx.graphics.getWidth();
height = Gdx.graphics.getHeight();
cam = new OrthographicCamera(width, height);
cam.setToOrtho(false);
cam.position.set(player.getX(), player.getY(), 0);
cam.update();
batch = new SpriteBatch();
batch.setProjectionMatrix(cam.combined);
sr = new ShapeRenderer();
}
public void update(float delta){
checkKeys();
player.update(delta);
cam.position.set(player.getX(), player.getY(), 0);
cam.unproject(new Vector3(player.getX(), player.getY(), 0));
cam.update();
batch.setProjectionMatrix(cam.combined);
sr.setProjectionMatrix(cam.combined);
}
public void render(float delta) {
update(delta);
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
batch.begin();
player.render(batch);
batch.end();
sr.begin(ShapeType.Line);
player.renderDebug(sr);
sr.end();
}
public void resize(int width, int height) {
}
//check key events
private void checkKeys(){
if(InputHandler.keyPress(InputHandler.getExitKey())){
exit();
}
}
//key events
private void exit(){
Gdx.app.exit();
}
public void hide() {
dispose();
}
public void pause() {}
public void resume() {}
public void dispose() {
batch.dispose();
player.dispose();
sr.dispose();
}
}
最佳答案
我认为这可能是您将相机设置为player.getX()或getY()的地方。该 X 和 Y 值指向玩家 Sprite 的角点。尝试将相机设置为
player.getX() + (player.getWidth() / 2)
和
player.getY() + (player.getHeight() / 2)
它应该是玩家 Sprite 的中心。
关于java - 如何将播放器置于 libgDX 相机的中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17936592/