Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

c# - Instantiate Object at mouse position

I have created a script which was supposed to instantiate gameobject according to mouse position but something has went wrong. And it is only being instantiated at one position and in the middle of the screen.

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;
        }
    }

}

Please tell me what is wrong with my script.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...