我不明白我的代码中发生了什么

问题描述 投票:0回答:1

我正在使用 Libgdx 制作游戏,目前正在实现地形生成。这是代码:

@Override
public void render(float delta) {
    ScreenUtils.clear(Color.BLACK);
    camera.update();
    spriteBatch.setProjectionMatrix(camera.combined);
    shapeRenderer.setProjectionMatrix(camera.combined);
    spriteBatch.begin();
    Project5.INSTANCE.landTiles.forEach(landTile -> {
        spriteBatch.draw(landTile.texture,landTile.x,landTile.y);
    });
    spriteBatch.end();
    shapeRenderer.begin(ShapeRenderer.ShapeType.Line);
    shapeRenderer.setColor(Color.GOLDENROD);
    shapeRenderer.circle(player.x,player.y,32);
    shapeRenderer.end();

    int speed=1000;
    if(Gdx.input.isKeyPressed(Input.Keys.W))
    {
        player.y+=delta*speed;
    }
    if(Gdx.input.isKeyPressed(Input.Keys.S))
    {
        player.y-=delta*speed;
    }
    if(Gdx.input.isKeyPressed(Input.Keys.A))
    {
        player.x-=delta*speed;
    }
    if(Gdx.input.isKeyPressed(Input.Keys.D))
    {
        player.x+=delta*speed;
    }
    camera.position.set(player.x,player.y,0);
    Vector2 cameraPosition=new Vector2(MathUtils.round(camera.position.x/Project5.chunkSize/64),MathUtils.round(camera.position.y/Project5.chunkSize/64));
    generateChunk(cameraPosition);
    generateChunk(cameraPosition.sub(1,1));
    System.out.println(Project5.INSTANCE.generatedChunks.size());
}

private void generateChunk(Vector2 cameraPosition) {
    ArrayList<Vector2> generatedChunks= Project5.INSTANCE.generatedChunks;
    if(!generatedChunks.contains(cameraPosition))
    {
        generatedChunks.add(cameraPosition);
        float nextX= cameraPosition.x*Project5.chunkSize;
        float nextY= cameraPosition.y*Project5.chunkSize;
        for (float x =nextX; x <nextX +Project5.chunkSize; x++) {
            for (float y=nextY;y<nextY+Project5.chunkSize; y++) {
                LandTile landTile = new LandTile(Project5.INSTANCE.water, (int) ((x-Project5.chunkSize/2) * 64), (int) (y-Project5.chunkSize/2)*64);
                Project5.INSTANCE.landTiles.add(landTile);
            }
        }
    }
}

由于某种原因,第二个“generateChunk”调用不断添加相同的向量。这是调试器显示的内容:

它显示它正在添加向量 0,0,但 generatedChunks 只包含向量 -1,-1。我是瞎子吗?这似乎是错误的。

libgdx
1个回答
0
投票

这是因为您一遍又一遍地添加相同的

Vector2
实例。

这个,

cameraPosition.sub(1,1)
不会返回新的
Vector2
,它只是更新现有的
cameraPosition

尝试改变

Vector2 cameraPosition=new Vector2(MathUtils.round(camera.position.x/Project5.chunkSize/64),MathUtils.round(camera.position.y/Project5.chunkSize/64));
generateChunk(cameraPosition);
generateChunk(cameraPosition.sub(1,1));

Vector2 cameraPosition=new Vector2(MathUtils.round(camera.position.x/Project5.chunkSize/64),MathUtils.round(camera.position.y/Project5.chunkSize/64));
generateChunk(cameraPosition);
generateChunk(new Vector2(cameraPosition.sub(1,1)));
© www.soinside.com 2019 - 2024. All rights reserved.