這一個讓我難住。我有三個類 - 一個名爲Level
的大類,其中包含指向Plant
實例的多維向量指針和指向Mob
實例的多維向量指針;這兩種載體都是根據它們的位置對暴徒和植物進行分類,以便我可以根據它們的大概位置在較小的矢量中搜索每個矢量,而不是騎自行車穿過所有現有的植物/小怪,以便找到最靠近給定點。向量中彈出的Ghost實例
向量如下,最小的std ::向量表示每邊有128個像素的正方形區域。通過將它們的X和Y座標分開128並將它們添加到適當的扇區中,可以將移動裝置和植物分類(我小心所得到的值實際上是整數)。
std::vector< std::vector< std::vector<Plant*> > >* m_PlantSectors
std::vector< std::vector< std::vector<Mob*> > >* m_AnimalSectors
小怪有時需要找到植物。這裏是問題出現的地方:當小怪查詢多維向量,在他們的近似區域搜索植物(如果怪物的座標是128,例如[1,2]它搜索m_PlantSectors [2] [1]),他們有時會找到不存在的植物。
不僅如此,而且這些植物有不可能的位置,例如1.9777e + 33或3.75853e-39(例如)。當我嘗試將所選植物的顏色改爲紅色以便直觀地發現它時,我發現屏幕上沒有任何植物(唯一植物是我手工放置的植物)改變了顏色。
我用一個整數ID標記了所有的植物;有36個植物,ID爲1-36,但我的小怪發現的植物具有63或429的ID--這些植物不可能存在,因爲沒有創建這樣的植物數量(有一個植物創建功能,一致地報告有多少植物存在,所以沒有植物被意外創造)。所有的怪物都在虛構的植物之後跑到屏幕的左上角,並死於飢餓。
所以不知何故,我創造了幽靈植物。到目前爲止,我已經嘗試了兩種單獨的方法來允許Mob
實例查找Plant
實例。第一個是這樣的:
float TargetDist = 256 * 256;
Plant* Candidate = 0;
Plant* ForageTarget = 0;
int xSect = m_X/128;
int ySect = m_Y/128;
std::vector<Plant*> ThisSect = pLevel->CheckPSector(xSect, ySect);
for (int i = 0; i < ThisSect.size(); ++i)
{
cout << "Searching in Sector (" << ySect << ", " << xSect << ")\n";
Candidate = ThisSect[i];
cout << "Candidate at: " << Candidate->GetX() << ", " << Candidate->GetY() << "\n";
Candidate->Mark();
//Calculate distance
float xDist = Candidate->GetX() - m_X;
float yDist = Candidate->GetY() - m_Y;
float tDist = sqrt(xDist * xDist + yDist * yDist);
if (tDist <= TargetDist)
{
ForageTarget = Candidate;
TargetDist = tDist;
}
}
凡CheckPSector()看起來是這樣的:
std::vector<Plant*> Level::CheckPSector(int x, int y)
{
return m_PlantSectors[y][x];
}
我嘗試的第二件事情是這樣的:
float TargetDist = 256 * 256;
Plant* Candidate = 0;
Plant* ForageTarget = 0;
int xSect = m_X/128;
int ySect = m_Y/128;
std::vector< std::vector< std::vector<Plant*> > >* Sectors = pLevel->AccessPlantSectors();
for (int i = 0; i < (*Sectors)[ySect][xSect].size(); ++i)
{
cout << "Searching in Sector (" << ySect << ", " << xSect << ")\n";
Candidate = (*Sectors)[ySect][xSect][i];
cout << "Candidate at: " << Candidate->GetX() << ", " << Candidate->GetY() << "\n";
Candidate->Mark();
//Calculate distance
float xDist = Candidate->GetX() - m_X;
float yDist = Candidate->GetY() - m_Y;
float tDist = sqrt(xDist * xDist + yDist * yDist);
if (tDist <= TargetDist)
{
ForageTarget = Candidate;
TargetDist = tDist;
}
}
使用此:
std::vector< std::vector< std::vector<Plant*> > >* Level::AccessPlantSectors()
{
return &m_PlantSectors;
}
然而,這兩個讓動物尋找想象中的植物並逃入空洞。
我不想定期複製潛在的大型多維向量到Mob
實例中,因爲在任何時候都會有很多這樣的實例,並且我希望程序運行得有點平穩。即便如此,我只是試圖通過複製整個向量而不是相關的向量來完成整個事情,並得到相同的結果:假想植物。
我從來沒有像以前那樣有過這樣的問題;這裏會發生什麼?
編輯:也許我應該提到,讓選擇的植物自我報告自己的位置和ID失敗的同樣,出現了荒謬的結果,所以它不僅僅是我用來訪問私人成員的Plant
中的函數。同時,查詢所有現有工廠並沒有透露鬼工廠自我報告的信息。
你的問題相當長,很難遵循。你可以考慮簡化你的代碼和場景,並創建一個自包含的測試用例嗎? (見http://sscce.org) –
是的,我想你是對的。我會看看我是否可以簡化一些東西 - 也許我會回答我自己的問題。 – GarrickW
我想知道你爲什麼使用多維數組的指針。聞起來像從未初始化的內存中讀取:) :) – LiMuBei