我正在嘗試找出一種方法,通過該方法我可以移動物件陣列中的專案,但將陣列中的某些專案保留在它們所在的位置,使上面的所有專案都低于固定專案。想想寶石匹配游戲,寶石可以匹配。以下是規則:
- 板可以是任何 X、Y 尺寸
- 棋盤上裝滿了寶石(可以破碎并因此被摧毀)和無法破碎的巖石(因此無法被摧毀)
- 巖石在它們的位置上是靜止的,不能移動。
- 當用戶匹配寶石時,它們會被銷毀,所有剩余的寶石都會下降到下一個可用空間。
- 如果匹配的寶石位于巖石下方,則巖石上方的寶石應跳過巖石位置并填充底部最開放的位置。
- 巖石可以堆疊 n 深,垂直或水平。
我的代碼有效,但前提是只有一塊石頭。請注意,這是為 Unity 用 C# 撰寫的,但解決方案不是 Unity 特定的(甚至不是 c#)。如果有兩塊石頭疊在一起,像這樣:
[Gem_1]
[Rock_1]
[Rock_2]
[Gem_2]
[Gem_3]
[Gem_4]
并且寶石 2,3 和 4 被摧毀,那么寶石應該都掉下來,看起來像這樣:
[Gem_7]
[Rock_1]
[Rock_2]
[Gem_6]
[Gem_5]
[Gem_1]
但是,使用我的代碼,當它們掉落時,它們看起來像這樣:
[Gem_7]
[Rock_1]
[Rock_2]
[Gem_1]
[Gem_6]
[Gem_5]
這是我的更新代碼:
private gem_script NextGem(Vector2Int currentGem)
{
for (int y = 0; y < board_height; y )
{
if(allGems[currentGem.x, y] != null && isGem(layoutStore[currentGem.x, y]) && y > 0){
return allGems[currentGem.x, y].GetComponent<gem_script>();
}
}
return null;
}
private IEnumerator ScrollNewGems()
{
for (int x = 0; x < board_width; x )
{
for (int y = 0; y < board_height; y )
{
if (layoutStore[x, y] != Gem_Type.empty)
{
if (allGems[x, y] == null)
{
Vector2Int current_gem_pos = new Vector2Int(x, y);
gem_script next_gem = NextGem(current_gem_pos);
if(next_gem != null)
{
Vector2Int next_gem_pos = next_gem.GetGemPos();
next_gem.SetGemXYPos(new Vector2Int(current_gem_pos.x, current_gem_pos.y));
allGems[x, y] = allGems[next_gem_pos.x, next_gem_pos.y];
allGems[next_gem_pos.x, next_gem_pos.y] = null;
}
}
}
}
}
}
編輯 我更新了我的代碼,但這僅在有一個 Gem 可供下拉時才有效。如果有不止一顆寶石,那么它們會留在頂部
uj5u.com熱心網友回復:
我編輯的腳本中有一個錯字。nextGem 函式不應該從 ay=0 開始,而是從 currentGem.y 開始。否則,它從頭開始。完整的作業代碼是:
private gem_script NextGem(Vector2Int currentGem)
{
for (int y = currentGem.y; y < board_height; y )
{
if(allGems[currentGem.x, y] != null && isGem(layoutStore[currentGem.x, y])){
return allGems[currentGem.x, y].GetComponent<gem_script>();
}
}
return null;
}
private IEnumerator ScrollNewGems()
{
gameState = GameState.Wait;
yield return new WaitForSeconds(.2f);
for (int x = 0; x < board_width; x )
{
for (int y = 0; y < board_height; y )
{
if (layoutStore[x, y] != Gem_Type.empty)
{
if (allGems[x, y] == null)
{
Vector2Int current_gem_pos = new Vector2Int(x, y);
gem_script next_gem = NextGem(current_gem_pos);
if(next_gem != null)
{
Vector2Int next_gem_pos = next_gem.GetGemPos();
next_gem.SetGemXYPos(new Vector2Int(current_gem_pos.x, current_gem_pos.y));
allGems[x, y] = allGems[next_gem_pos.x, next_gem_pos.y];
allGems[next_gem_pos.x, next_gem_pos.y] = null;
}
}
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/395987.html
上一篇:找出給定演算法的復雜度
