2016-11-08 129 views
0

我試圖創建標記我可以訪問的單元格的對象。我將它們標記爲紅色方形:Physics.CheckSphere總是提供假(Unity3D)

enter image description here enter image description here

我創建對象代碼:

using UnityEngine; 
using System.Collections; 
using System; 

public class SpawnCheck : MonoBehaviour { 

    public GameObject checkObject; 

    public bool canSpawnCheck = true; 
    Vector2 boxSize; 

    public GameObject spawnedObject; 
    // Use this for initialization 
    void Start() { 
     Debug.Log("Into spawn check"); 
    } 

    void OnTriggerEnter2D(Collider2D other) { 
     Debug.Log("Enter trigger collision"); 
     canSpawnCheck = false; 

     if (other.gameObject.tag == "Target") { 
      Debug.Log ("Found Target"); 
     } 

     if (other.gameObject.tag == "Wall") { 
      canSpawnCheck = false; 
     } 

     if (other.gameObject.tag == "Check") { 
      canSpawnCheck = false; 
     } 
    } 

    void OnTriggerExit2D(Collider2D other) { 
     Debug.Log("Exit trigger collision"); 
     canSpawnCheck = true; 
    } 

    // Update is called once per frame 
    void Update() { 

     Debug.Log ("canSpawnCheck " + canSpawnCheck); 

     if (canSpawnCheck == true) { 

      Vector3 currentPosition = this.gameObject.transform.position; 
      Vector3 spawnPos = new Vector3 (Mathf.Round (currentPosition.x), Mathf.Round (currentPosition.y),0); 

      Debug.Log ("Physics.CheckSphere " + Physics.CheckSphere (spawnPos, 5)); 

      if (!Physics.CheckSphere(spawnPos,5)) { 

       spawnedObject = (GameObject)Instantiate (checkObject, spawnPos, Quaternion.identity); 

       this.gameObject.GetComponentInParent<AILerp>().possibleTargets.Add (spawnedObject); 
      } 
     } 

    } 
} 

我的問題:Physics.CheckSphere(spawnPos,5)總是返回false我的代碼滋生太多的紅色方塊和產卵他們在彼此。我只想創建一次紅色方塊,並且從不在牆上創建(白色方塊)。

+0

我只想指出一件事。您應該在'OnTriggerEnter2D'方法中使用'Equals()'方法而不是'=='進行字符串比較。 – greenPadawan

+0

您是否檢查過確實有一個或多個碰撞體與中心** spawnPos **和半徑5定義的球體重疊? – greenPadawan

+0

@greenPadawan我可以檢查它嗎? – IlyaGutnikov

回答

1

您的檢查(克隆)遊戲對象有Box Collider 2D附加到它。因此,你必須使用的每個物理功能應該是Physics2D.something而不是Physics.something。注意那裏的關鍵詞「2D」。

如果您只使用Box Collider而沒有2D,那麼您可以使用Physics.something。所以,Physics.CheckSphere不能與2D對撞機一起使用。

檢查(克隆)SpriteRenderer,2D Collider是合適的。您只需使用Physics2D重疊函數中的一個,例如Physics2D.OverlapBox,Physics2D.OverlapAreaPhysics2D.OverlapCircle。哪一個你喜歡。