简体   繁体   English

在鼠标位置实例化对象

[英]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. 请告诉我我的脚本出了什么问题。

The problem is that Input.mousePosition does not have z-axis because there is only x and y axis for mouse coordinate. 问题在于Input.mousePosition没有z轴,因为鼠标坐标只有x和y轴。 The z axis is simply 0 therefore returning wrong position when Camera.main.ScreenToWorldPoint is used. z轴只是0因此在使用Camera.main.ScreenToWorldPoint时返回错误的位置。

You need to do Input.mousePosition; 您需要执行Input.mousePosition; , manually modify it's z-axis value to be anything > 0 . ,手动将其z轴值修改为> 0 Usually, 10 is fine for this but you can modify it if it is not enough for you. 通常, 10就可以了,但是如果您不够的话,可以修改它。 After that, you can then pass that modified Vector3 to the Camera.main.ScreenToWorldPoint(mousepos) function. 之后,您可以将修改后的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;
    }
}

Not related: 不相关的:

I noticed that you are using Input.GetMouseButton . 我注意到您正在使用Input.GetMouseButton You probably want Input.GetMouseButtonDown as Input.GetMouseButtonDown is called once until the key is released. 您可能希望Input.GetMouseButtonDown作为Input.GetMouseButtonDown被调用一次,直到释放键。 Input.GetMouseButton is repeatedly called when the pressed key is held down and you can easily create thousands of objects with that. 按住此键时,会反复调用Input.GetMouseButton ,您可以轻松地创建数千个对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM