遊戲場景切換或「重新開始」時,怪物生成位置錯誤:不在初始位置,而是接上一局的偏移量。
void Cms::showMonster(CCArray* monsterArray, int type) {
static int posN = 0; // ← 靜態局部變量
for (int i = 0; i < monsterArray->count(); i++) {
auto monsterSprite = (CCSprite*)monsterArray->objectAtIndex(i);
if (type == 1)
monsterSprite->setPosition(ccp(640 + posN * 480, 4*32 - 16));
else if (type == 2)
monsterSprite->setPosition(ccp(160 + posN * 640, 192*2));
this->addChild(monsterSprite);
posN++;
}
}
static int posN = 0; 定義在函數內部 → 靜態局部變量。Cms 對象可能被銷毀重建,但 posN 不會重置,保持上一局的最終值。posN 已非 0,怪物位置偏移。class Cms {
int monsterPosIndex_ = 0; // 成員變量,隨對象生命週期
public:
void showMonster(CCArray* monsterArray, int type) {
int posN = monsterPosIndex_; // 局部拷貝或直接用成員
for (...) { ... posN++; }
monsterPosIndex_ = posN; // 若需跨調用保持,否則每次重置為 0
}
void reset() { monsterPosIndex_ = 0; } // 重新開始時調用
};
優點:隨 Cms 對象創建/銷毀自動重置,符合遊戲邏輯「每局重新開始」。
void Cms::showMonster(...) {
static int posN = 0;
// ... 使用 posN ...
}
void Cms::resetMonsterCounter() { // 靜態成員函數或友元
// 無法直接訪問函數內靜態變量,需改為類靜態成員
}
不推薦:破壞封裝,難以維護。
void showMonster(CCArray* arr, int type, int& posIndex) { ... }
調用方管理計數器,完全可控。
static Instance* instance; 在場景切換時未清理,導致舊場景資源殘留、記憶體洩漏。需在 Director::getInstance()->replaceScene() 時手動 destroyInstance()。static Vector cache; 累積跨場景對象,引用計數不降,導致釋放失敗。場景切換時必須 clear() 並 release()。static bool seeded = false; if(!seeded){srand(time(0));seeded=true;} 只種一次,若需每局不同隨機序列,應每局 srand。static 是否必要?生命週期是否匹配業務邏輯?