2017-05-08 204 views
0

因此,我正在製作一個馬里奧製造商「克隆」,我希望它實例化對象,當我舉行控制和拖動。它使幾乎無限的瓷磚。如果新位置與對象的舊位置相同,我希望它只生成一個對象。一切由1塊鼠標拖動克隆無限克隆

public GameObject tilePrefab; 

     void OnMouseDrag(){ 
     Vector2 pos = Input.mousePosition; 
     pos = Camera.main.ScreenToWorldPoint (pos); 
     pos.x = Mathf.Round(pos.x); 
     pos.y = Mathf.Round(pos.y); 
     transform.position = pos; 
     if (Input.GetKey (KeyCode.LeftControl)) { 
      if (transform.position != GameObject.Find ("SomePrefabName").transform.position) { 
       GameObject myGameObject = Instantiate (tilePrefab) as GameObject; 
       myGameObject.name = "SomePrefabName"; 
      } 
     } 
    } 

Before Drag

After Drag

回答

1

嘗試更改爲這個捕捉到的1網格:

public GameObject tilePrefab; 
     void OnMouseDrag(){ 
     Vector2 pos = Input.mousePosition; 
     pos = Camera.main.ScreenToWorldPoint (pos); 
     pos.x = Mathf.Round(pos.x); 
     pos.y = Mathf.Round(pos.y); 
     transform.position = pos; 
     var hitColliders = Physics.OverlapSphere(transform.position, 1); 
     if (Input.GetKey (KeyCode.LeftControl)) { 
      if (hitColliders.Length == 0) { 
       GameObject myGameObject = Instantiate (tilePrefab) as GameObject; 
       myGameObject.name = "SomePrefabName"; 
      } 
     } 
    } 

這裏我們使用Physics.OverlapSphere來檢測,如果我們在想要的位置有一個對撞機,如果不是,在這種情況下,我們繼續執行代碼

+0

理論上應該有效,但是當我這樣做的時候似乎並沒有發生。我嘗試改變價值觀,我所得到的更加分散。 – racorse

+0

對不起,我知道你可能已經修復了這個問題,但是問題可能會通過將Input.GetKey更改爲Input.GetKeyUp –