我創(chuàng)建了一個(gè)由 10 個(gè)單位立方組成的對(duì)象網(wǎng)格系統(tǒng),并將它們添加到列表中。我試圖讓列表中的每個(gè)對(duì)象通過(guò)它們?cè)诰W(wǎng)格中的位置(通過(guò)變量 posX 和 posY)相互檢測(cè)(topContact、leftContact、rightContact、bottomContact)。當(dāng)我在運(yùn)行時(shí)檢查分配時(shí),我發(fā)現(xiàn)具有空觸點(diǎn)的對(duì)象,尤其是bottomContact。我已經(jīng)嘗試過(guò)Mathf.Approximately,以防萬(wàn)一這是一個(gè)浮動(dòng)問(wèn)題,我已經(jīng)檢查并確認(rèn) gridList 是完整的并且沒(méi)有重復(fù)項(xiàng)。在運(yùn)行時(shí),每個(gè) gridLabel 對(duì)象上的 posX 和 posY 都會(huì)被正確識(shí)別。using System.Collections;using System.Collections.Generic;using UnityEngine;public class GridLabel:MonoBehaviour { Director director; public float posX; public float posY; public string gridLabel; public GridLabel topContact = null; public GridLabel leftContact = null; public GridLabel rightContact = null; public GridLabel bottomContact = null; void Awake() { director = FindObjectOfType<Director>(); UpdateName(); PopulateContacts(); } private void UpdateName() { posX = (transform.position.x + 35) / 10; posY = (transform.position.y - 10) / 10; gridLabel = posX + "," + posY; gameObject.name = gridLabel; } void PopulateContacts() { foreach(GridLabel grid in director.gridList) { if(Mathf.Approximately(posX,grid.posX) && Mathf.Approximately(posY,grid.posY + 1f)) { topContact = grid; } else if(Mathf.Approximately(posX,grid.posX - 1f) && Mathf.Approximately(posY,grid.posY)) { leftContact = grid; } else if(Mathf.Approximately(posX,grid.posX + 1f) && Mathf.Approximately(posY,grid.posY)) { rightContact = grid; } else if(Mathf.Approximately(posX,grid.posX) && Mathf.Approximately(posY,grid.posY - 1f)) { topContact = grid; } } }}除了邊框 gridLabel 對(duì)象之外,我希望所有四個(gè)接觸都與相鄰的 gridLabel 完成。再次,我經(jīng)常發(fā)現(xiàn)丟失的聯(lián)系人,尤其是底部聯(lián)系人。這個(gè)問(wèn)題可能很簡(jiǎn)單,但我對(duì) C# 和一般編碼相對(duì)較新。提前感謝您提供的任何幫助。
2 回答

慕姐8265434
TA貢獻(xiàn)1813條經(jīng)驗(yàn) 獲得超2個(gè)贊
在最后一個(gè)else if塊中你再次使用了
topContact = grid;
我想它應(yīng)該在bottomContact這里
else if(Mathf.Approximately(posX, grid.posX) && Mathf.Approximately(posY, grid.posY - 1f))
{
bottomContact = grid;
}

鳳凰求蠱
TA貢獻(xiàn)1825條經(jīng)驗(yàn) 獲得超4個(gè)贊
在最后一個(gè)else if塊中你再次使用了
topContact = grid;
我想它應(yīng)該在bottomContact這里
else if(Mathf.Approximately(posX, grid.posX) && Mathf.Approximately(posY, grid.posY - 1f))
{
bottomContact = grid;
}
- 2 回答
- 0 關(guān)注
- 212 瀏覽
添加回答
舉報(bào)
0/150
提交
取消