使用 camera.unproject 重新渲染纹理会在摄像机移动时设置错误的位置



>问题

当我移动摄像机时,渲染的每个纹理都会在屏幕上以 2 个不同的位置闪烁。

我想要什么

示例:当我将相机向左移动时,我希望所有纹理向右移动 32 像素。相机每按下按钮移动 32 像素。

当前代码

我在评论中添加了一些额外的解释。

主程序入口点

/**
* DefaultCamera: Setting up OrthographicCamera
* CameraMovement: Using camera.translate on keypresses to move the screen.
* TestMoveable: Creating a texture for testing rendering.
*/
public class WorldSimGame extends ApplicationAdapter {
private DefaultCamera defaultCamera;
private CameraMovement cameraMovement;
private TestMoveable testMoveable;
// Setting up the camera and texture.
public void create ()  {
defaultCamera = new DefaultCamera();
cameraMovement =  new CameraMovement(defaultCamera.getCamera());
testMoveable = new TestMoveable();
testMoveable.create(defaultCamera);
}
// The testMoveable.render(defaultCamera) should keep track of the  testMoveable position
public void render ()  {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
defaultCamera.render();
testMoveable.render(defaultCamera);
}
}

测试可移动

public class TestMoveable {
private Texture tex;
private SpriteBatch batch;
private Vector3 position;
public void create(DefaultCamera defaultCamera) {
tex = new Texture(("wall.png"));    
batch = new SpriteBatch();
position = new Vector3(100, 100, 0);
defaultCamera.getCamera().unproject(position);
}

我无法想象在世界坐标上设置 x 和 y 坐标是行不通的。

public void render(DefaultCamera defaultCamera) {       
batch.begin();
batch.draw(tex, position.x, position.y);
batch.end();
}
}

我在这里做错了什么?有没有更好的方法来为渲染器实现位置检查?

您无需检查渲染器的位置。您所要做的就是 设置camera的大小和位置 .然后用batch.setProjectionMatrix(camera.combined)说出批来绘制相机看到的内容。

因此,当您创建大小 = 50x50 且位置 = 100,100的相机时,您现在创建一个大小 = 50x50
且位置 = 75,75
Texture纹理将完全适合孔屏幕。

相机的位置在中心。所以Texture的位置是 75,75 而不是 100,100

当您现在要移动相机时,您可以使用方法:translate()相机。
呼叫:camera.translate(25,0)将相机向右移动 25 个单位,现在您只能在屏幕左侧看到一半的Texture

这是可移动相机的简单示例。您可以使用箭头键四处移动:

public class WorldSimGame extends ApplicationAdapter {
private OrthographicCamera camera;
private SpriteBatch batch;
private Texture texture;
public WorldSimGame() { }
@Override
public void create(){
//Create texture, batch and camera
texture = new Texture(Gdx.files.internal("badlogic.jpg"));
batch = new SpriteBatch();
camera = new OrthographicCamera(60,60);
}
@Override
public void render(){
//clear screen
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
moveCamera();
//update camera that he recalculate his position and Matrix
camera.update();
batch.setProjectionMatrix(camera.combined); //set batch to draw what the camera sees
batch.begin();
batch.draw(texture,0,0); //draw texture
batch.end();
}
private void moveCamera(){
//move camera
if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)){
camera.translate(4,0);
}
if(Gdx.input.isKeyPressed(Input.Keys.LEFT)){
camera.translate(-4,0);
}
if(Gdx.input.isKeyPressed(Input.Keys.UP)){
camera.translate(0,4);
}
if(Gdx.input.isKeyPressed(Input.Keys.DOWN)){
camera.translate(0,-4);
}
}
}

最新更新