2017-04-15 99 views
1

我已經創建了一個腳本,該腳本應該根據鼠標位置實例化遊戲對象,但出現了一些問題。它只在屏幕的一個位置和中間被實例化。在鼠標位置實例化對象

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

public class LineInstantiater : MonoBehaviour { 

    public GameObject lineprefab; 
    private GameObject linehandler; 
    private Vector3 mousepos; 

    void Update(){ 
     if (Input.GetMouseButton (0)) { 
      mousepos = Camera.main.ScreenToWorldPoint (Input.mousePosition); 
      linehandler = Instantiate (lineprefab,Camera.main.ScreenToWorldPoint(Input.mousePosition),Quaternion.identity) as GameObject ; 
      linehandler.transform.position = mousepos; 
     } 
    } 

} 

請告訴我我的腳本有什麼問題。

+0

嗨,你的問題是什麼?什麼地方出了錯?如果您發現任何錯誤,請發佈。 – Programmer

+0

@編程器檢查編輯。我總是忘記提及 –

+0

對不起,但我們不知道你的問題是什麼。 「在一個位置實例化」是什麼意思?預製件沒有實例化鼠標箭頭的位置?這是什麼類型的對象? UI,2D或3D對象?我建議你張貼屏幕截圖 – Programmer

回答

2

問題是Input.mousePosition沒有z軸,因爲鼠標座標只有x和y軸。軸z只是0,因此在使用Camera.main.ScreenToWorldPoint時返回錯誤的位置。

您需要做Input.mousePosition;,手動修改它的Z軸值爲> 0。通常,10對此適用,但如果對您不夠,則可以對其進行修改。之後,您可以將修改後的Vector3傳遞給Camera.main.ScreenToWorldPoint(mousepos)函數。

public GameObject lineprefab; 
private GameObject linehandler; 
private Vector3 mousepos; 

void Update() 
{ 
    if (Input.GetMouseButtonDown(0)) 
    { 
     mousepos = Input.mousePosition; 
     mousepos.z = 10; 

     mousepos = Camera.main.ScreenToWorldPoint(mousepos); 
     linehandler = Instantiate(lineprefab, mousepos, Quaternion.identity) as GameObject; 
    } 
} 

OR

public GameObject lineprefab; 
private GameObject linehandler; 

void Update() 
{ 
    if (Input.GetMouseButtonDown(0)) 
    { 
     Ray rayCast = Camera.main.ScreenPointToRay(Input.mousePosition); 
     linehandler = Instantiate(lineprefab, rayCast.GetPoint(10), Quaternion.identity) as GameObject; 
    } 
} 

沒有關係:

我注意到,您正在使用Input.GetMouseButton。您可能想要Input.GetMouseButtonDown,因爲Input.GetMouseButtonDown被調用一次直到密鑰被釋放。當按下的按鍵被按下時,反覆調用Input.GetMouseButton,您可以輕鬆地創建數千個對象。