gpt4 book ai didi

c++ - 调用存储在 map 中的类中的函数

转载 作者:行者123 更新时间:2023-11-28 01:46:42 24 4
gpt4 key购买 nike

我最近开始更多地使用 C++,为了更好地使用它,我正在创建一个基本的体素游戏,它是我在学习 Java 时所做的事情的克隆。 (想想基本的我的世界)

主游戏循环调用 World 类中的 draw() 方法,然后循环遍历所有 block 并在 block 上调用 draw 方法。为了既节省内存使用量,又为了拥有非方形世界, block 存储在 map 中,其中键是一个类,该类将 block 位置存储在 chunk space 中。 ( block 空间本质上是 chunkx = floor(worldx/chunksize))

我相信我目前在 map 中的 chunks 上调用 .draw() 函数的方式不正确,因为代码构建应该只被调用一次的 block 网格被一遍又一遍地调用。

世界的绘制函数:

void World::draw () {
std::map<ChunkPosition, Chunk>::iterator it = chunks.begin();
while (it != chunks.end()) {
ChunkPosition pos = it->first;
Chunk chunk = it->second; // I think I may need to use a pointer here somehow

chunk->draw();
it++;
}
}

Chunk的绘制函数:

void Chunk::draw () {
if(build){ // should only "build" the mesh once, is initialized to true
build = false;

... mesh building code that is not relevant ...

std::cout << verticeSize << std::endl; // this is called every loop cycle instead of once

mesh.build (vertices, verticeSize, indices, indiceSize);
}

mesh.draw(); // draw the mesh every cycle
}

这是 Chunk 类的结构

class Chunk {
private:
static const int size = 25;
std::map<Location, Block> blocks;
Mesh mesh;
bool build = true;
public:
void setBlock (Location, Block&);
void setBlock (int, int, int, Block&);
Block *getBlock (Location);
Block *getBlock (int, int, int);
bool hasBlock (Location);
bool hasBlock (int, int, int);
void draw ();
};

我在 chunks 映射中的 (0,0,0) 位置有一个 block 。关于它的其他一切都与问题无关。

最佳答案

一个问题是您正在复制存储在 map 中的区 block :

Chunk chunk = it->second;

您应该改为访问引用。这可以像这样完成:

Chunk& chunk = it->second;

但使用基于范围的 for 循环而不是复杂的 while 循环可能更容易:

for (auto& chunk : chunks) chunk.second.draw();

关于c++ - 调用存储在 map 中的类中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44769719/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com