【发布时间】:2020-07-17 17:50:44
【问题描述】:
我正在尝试用 C++ 为我正在开发的游戏构建一个库存系统。但是,当我调用Inventory::AddItem(Item i) 时,库存系统中有一个错误,没有添加任何物品,并且该插槽仍然保持空白。目前,我通过std::vector<Item>处理库存,其中Item是一个包含类型的结构,如果它是可堆叠的,堆栈中的最大块数,堆栈中的当前块数,以及几个对象动画。此外,我自动在库存中填充了 40 个空气块插槽,其 ID 为INVENTORY_EMTPY_SLOT_ID.
代码如下:
typedef struct item {
int type; // this is whether the block is a foreground of background tile
int id; // use this for the id of objects
bool stackable; // true indicates that the block can be stacked
int max_num; // maximum number of blocks in a stack
int num; // the current number of blocks in the stack
Animation* use_animation; // the animation of the block or item when it is being used
Animation* other_animation; // secondary animation of item in case it is necessary
} Item;
我如何初始化空槽:
for (size_t x = 0; x < INVENTORY_MAX_SLOTS; x++) {
Item i = {0, INVENTORY_EMPTY_SLOT_ID, true, 1, 1, NULL, NULL};
this->items.push_back(i);
}
添加项目
/*********BUG HERE:******************/
void Inventory::AddItem(Item item) {
// find all indexes with the same item.id
std::vector<size_t> indexes_w_same_item;
for (size_t i = 0; i < this->items.size(); i++) {
if (this->items[i].id == item.id) {
indexes_w_same_item.push_back(i);
}
}
// find the next empty slot
int next_empty_slot = -1;
for (size_t i = 0; i < this->items.size(); i++) {
if (this->items[i].id == INVENTORY_EMPTY_SLOT_ID) {
next_empty_slot = i;
}
}
// go through all the indexes with the same item.id
// and see if at least one of them is empty.
// if one is empty and has sufficient capacity,
// add the item and return. if it isn't, keep moving forward
for (size_t x = 0; x < indexes_w_same_item.size(); x++) {
if (item.id == this->items[indexes_w_same_item[x]].id) {
if (this->items[indexes_w_same_item[x]].num + item.num <= this->items[indexes_w_same_item[x]].max_num) {
this->items[indexes_w_same_item[x]].num += item.num;
return;
}
}
}
// if there is an empty slot, make a new stack
if (next_empty_slot >= 0) {
this->items[next_empty_slot].id = item.id;
this->items[next_empty_slot].max_num = item.max_num;
// clamp item.num so it doesn't exceed item.max_num
if (item.max_num > item.num) {
this->items[next_empty_slot].num = item.num;
} else {
this->items[next_empty_slot].num = item.max_num;
}
}
}
【问题讨论】:
-
我认为问题在于您没有将
Item设置为最后一个if语句中的下一个空插槽,您只需更改Item的属性即可那里。你如何初始化你的vector?你用空白项目填充它吗?或者你只是reserve一些空间? -
@melk,我刚刚编辑了问题,向您展示了我如何初始化空插槽。另外,关键是我有一个独特的
Item,每个插槽都有一个特定项目的数量。这样做是为了节省内存 -
那为什么不直接做
this->items[next_empty_slot] = item呢?另外,我会确保Item的构造函数强制执行不变量num > max_num,因此您不必稍后再检查。此外,根据您构建循环的方式,您将始终在vector末尾添加Items。
标签: c++ game-development