Instantiate Object at mouse position

前端 未结 1 1175

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 posit

相关标签:
1条回答
  • 2020-12-07 00:26

    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.

    0 讨论(0)
提交回复
热议问题