The problem is that Input.mousePosition
does not have z-axis because there is only x and y axis for mouse coordinate. The z
axis is simply 0
therefore returning wrong position when Camera.main.ScreenToWorldPoint
is used.
You need to do Input.mousePosition;
, manually modify it's z-axis value to be anything > 0
. Usually, 10
is fine for this but you can modify it if it is not enough for you. After that, you can then pass that modified Vector3
to the Camera.main.ScreenToWorldPoint(mousepos)
function.
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;
}
}
Not related:
I noticed that you are using Input.GetMouseButton
. You probably want Input.GetMouseButtonDown
as Input.GetMouseButtonDown
is called once until the key is released. Input.GetMouseButton
is repeatedly called when the pressed key is held down and you can easily create thousands of objects with that.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…