创建怪物并设置tiledMap的位置#java #libGDX

Create monster and set position of tiledMap #java #libGDX

我在地图上设置怪物时遇到问题。首先,我用相机坐标创建了一个骑士。现在我想在地图上设置一个独立于相机坐标的怪物,这样当我使用键移动玩家时,怪物会停留在一个位置。我试图实现这一点,但我得到的只是怪物一直停留在屏幕的左下角。这是我的人 class

public abstract class Person implements Stats {

public Person(String pathToFile,Vector2 position) {
    ...
}

public void update(float delta) {
    spriteBatch.begin();
    sprite.draw(spriteBatch);
    spriteBatch.end();
}

还有我的机器人 class

public class Bot extends Person {

public Bot() {
    super(toFilePath,new Vector2(500,550));
    super.position.set(500,550);
}

@Override
public void update(float delta) {
    super.update(delta);
}

@Override
public void dispose() {
    super.dispose();
}

}

骑士class

 public class Knight extends Person {

public Knight(OrthographicCamera camera) {

    super(toFilePath, new Vector2(MapScreen.startPositionX, MapScreen.startPositionY));
    super.sprite.setCenter(camera.viewportWidth / 2, camera.viewportHeight / 2);
    this.camera = camera;
    // animation
    ...
}

public void update(float delta, MapScreen mapScreen) {
    camera.update();
    walkBatch.begin();
    // input handling
    walkBatch.end();
}

@Override
public void dispose() {
    ...
}

以及我设置所有 classes

的 class
public class MapScreen implements Screen {

...

@Override
public void show() {
    init(startPositionX, startPositionY);
}

// initialize variable
private void init(float posX, float posY) {
    camera = new OrthographicCamera();
    camera.setToOrtho(false, width, height);
    tiledMap = new TmxMapLoader(new ExternalFileHandleResolver()).load(mapName);
    setTiledMapRenderer(new OrthogonalTiledMapRenderer(tiledMap));
    knight = new Knight(camera);
    camera.zoom = ZOOM;
    camera.position.set(posX, posY, 0);
    camera.update();
}

@Override
public void render(float delta) {
    camera.update();
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    getTiledMapRenderer().setView(camera);
    getTiledMapRenderer().render(layerBottom);
    knight.update(delta, this);

    getTiledMapRenderer().render(layerTop);
}

当使用 SpriteBatch 时(在查看代码时,您可能根本不会使用它),然后您可以使用相机的矩阵来正确计算偏移量。

像这样使用它:

spriteBatch.setProjectionMatrix(camera.combined);
spriteBatch.begin();
// draw your sprites here
spriteBatch.end();

然后您还应该考虑通过不在屏幕外渲染精灵来提高性能:

Consider implementing some of the tips

我找到了解决办法。我在 Tiled 中创建了一个对象层,并在那里设置了我的怪物。然后在 MapScreen 中渲染它。谢谢你的帮助。