我有一個遊戲有點像我的世界,但從頂部向下的角度來看,添加塊是由玩家左鍵單擊它時添加塊在指定的位置,右鍵單擊放置的塊將刪除該塊。列表交叉引用導致c中的滯後#
我遇到的問題是,當玩家左鍵單擊它時,會將該塊及其位置添加到列表中(以便稍後保存到XML),所以合理的結論是,當玩家右擊它從遊戲中移除所述塊,並從其列表中移除所述塊。
這是我用其產生滯後的方法:
for (int b = 0; b < game.blocklist.Count; b++)
{
for (int v = 0; v < game.blockpos1.Count; v++)
{
if (game.blocklist[b].visible == true)
{
if (game.cursor.boundingbox.Intersects(game.blocklist[b].blockrectangle) && mousestate.RightButton == ButtonState.Pressed && game.player.Builder == true)
{
if (game.blocklist[b].blockposition.X == game.blockpos1[v].X && game.blocklist[b].blockposition.Y == game.blockpos1[v].Y)
{
game.blockpos1.RemoveAt(v);
game.blocklist.RemoveAt(b);
break;
}
}
}
}
}
現在這是我取代它與極大減少滯後並仍然達到予想的效果相同的方法:
for (int b = 0; b < game.blocklist.Count; b++)
{
if (game.blocklist[b].visible == true)
{
if (game.cursor.boundingbox.Intersects(game.blocklist[b].blockrectangle) && mousestate.RightButton == ButtonState.Pressed && game.player.Builder == true)
{
if (game.blocklist[b].blockposition.X == game.blockpos1[b].X && game.blocklist[b].blockposition.Y == game.blockpos1[b].Y)
{
game.blockpos1.RemoveAt(b);
game.blocklist.RemoveAt(b);
break;
}
}
}
}
爲什麼這會產生很多滯後?我只需要澄清我做錯了什麼,所以我不會再這樣做。
您似乎已經有效地減半執行這種方法的時間。你有兩個循環可以代替一個循環,並繼續遵守你的要求..歡迎來到重構的世界:) –