我有一个视口和相机设置,但每当我渲染时,视口都充当StretchViewport并填充整个屏幕,而不是保持纵横比并添加黑条。有谁知道,我做错了什么或如何解决它?
我在GameScreen类中获取此代码来设置相机和视口:
private static final int VIRTUAL_WIDTH = 468;
private static final int VIRTUAL_HEIGHT = 293;
private OrthographicCamera camera;
private FitViewport viewport;
@Override
public void show() {
camera = new OrthographicCamera();
viewport = new FitViewport(VIRTUAL_WIDTH,VIRTUAL_HEIGHT,camera);
viewport.apply();
camera.position.set(camera.viewportWidth/2,camera.viewportHeight/2,0);
}
@Override
public void render(float delta) {
camera.update();
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
batch.begin();
// do drawing
batch.end();
}
@Override
public void resize(int width, int height) {
viewport.update(width,height);
camera.position.set(camera.viewportWidth/2,camera.viewportHeight/2,0);
}
完整代码:
package com.Sidescroll.game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.utils.viewport.FitViewport;
public class GameScreen implements Screen {
private static final int VIRTUAL_WIDTH = 468;
private static final int VIRTUAL_HEIGHT = 293;
private SpriteBatch batch;
private BitmapFont font;
private OrthographicCamera camera;
private FitViewport viewport;
private int deltaCount;
private float deltaSum;
private float fps;
private Level level;
private Player player;
@Override
public void show() {
level = new Level();
player = new Player(level.getSpawn());
batch = new SpriteBatch();
font = new BitmapFont();
camera = new OrthographicCamera();
viewport = new FitViewport(VIRTUAL_WIDTH,VIRTUAL_HEIGHT,camera);
viewport.apply();
System.out.println(camera.viewportWidth);
camera.position.set(camera.viewportWidth/2,camera.viewportHeight/2,0);
}
@Override
public void render(float delta) {
camera.update();
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
player.update(delta);
deltaCount += 1;
deltaSum += delta;
if(deltaSum >= 1) {
fps = 1/(deltaSum/deltaCount);
deltaCount = 0;
deltaSum = 0;
}
batch.setProjectionMatrix(camera.combined);
batch.begin();
level.draw(batch, player);
font.draw(batch, "FPS: " + fps, 0, 293);
batch.end();
}
@Override
public void resize(int width, int height) {
viewport.update(width,height);
camera.position.set(camera.viewportWidth/2,camera.viewportHeight/2,0);
}
@Override
public void pause() {}
@Override
public void resume() {}
@Override
public void hide() {}
@Override
public void dispose() {
font.dispose();
batch.dispose();
level.dispose();
}
}
答案 0 :(得分:0)
忘记在课程延伸游戏中调用resize
@Override
public void resize(int width, int height) {
super.resize(width, height);
}