我最近才开始使用 libGDX 制作游戏,并且我正在尝试实现一个正交相机,以便在玩家移动时让他放松(制作一个 2D 横向滚动条)。出于某种原因,当我做所有应该使相机将玩家绘制在屏幕中央的事情时,我不明白,玩家被稍微移向右上角。
我整天都在寻找不同的东西,但我没有找到任何解决方案。
如果它有助于我的播放器精灵是一个 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();
}
}