2017-04-18 54 views
0

我想能夠實例化鼠標所在的對象。我試圖做到這一點(下面的代碼),但在我的嘗試中,對象總是在屏幕中心產生。我能做些什麼來解決這個問題?如何在鼠標光標處產生對象

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 

public class CraftingControl : MonoBehaviour 
{ 

    public GameObject[] selectedObjectArray = new GameObject[3]; 
    public GameObject selectedObject; 
    // Use this for initialization 


    void Update() 
    { 
     if (selectedObject == null) 
     { 
      return; 
     } 
     if (Input.GetMouseButtonDown(0))//Here im getting postion and spawning objects 
     { 
      Vector3 tempMousePost = Input.mousePosition; 
      Vector3 mousePost = Camera.main.ScreenToWorldPoint(tempMousePost); 
      mousePost.y = 0; 
      Instantiate(selectedObject, mousePost, transform.rotation); 

     } 

    } 
    void OnGUI() 
    { 

     if (Input.GetKey(KeyCode.C)) 
     { 
      GUI.Box(new Rect(100, 100, 300, 300), "Crafting"); 
      if (GUI.Button(new Rect(125, 125, 100, 50), "Campfire")) 
      { 
       selectedObject = selectedObjectArray[0]; 
      } 

      if (GUI.Button(new Rect(125, 200, 100, 50), "Tent")) 
      { 
       selectedObject = selectedObjectArray[1]; 
      } 
      if (GUI.Button(new Rect(125, 275, 100, 50), "Fence")) 
      { 
       selectedObject = selectedObjectArray[2]; 
      } 
     } 
    } 
} 
+0

你構建一個2D或3D遊戲? – pasotee

+0

@pasotee將一個2D物體放入一個3d世界將會很有趣,特別是如果我們不知道它應該如何放置的話。 –

+2

您不應該在遊戲開發中使用'OnGUI'(又名「立即模式GUI」)。它僅用於創建編輯器控件您需要使用新的[UI系統](https://docs.unity3d.com/Manual/UISystem.html)。 –

回答

4

我認爲相應於相機的鏡頭回報Camera.ScreenToWorldPoint點在世界上。它不會返回鼠標下的幾何體的世界座標,我懷疑是你想要的。爲此,您需要在場景中進行光線投射並找到交點所在的位置。

0

我建議你在鼠標位置光線投射,並設置Z值回來,如果你要一個2D項目:

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 
RayCastHit rayHit; 
     if (Physics.Raycast(ray, out rayHit)) 
     { 
      Vector3 position = rayHit.point; 
      position.z = 0f; 
      Instantiate(yourGameObject, position, Quaternion.Identity); 
     }