在鼠标位置实例化对象
我已经创建了一个脚本,它应该根据鼠标位置实例化gameobject,但是出了问题。 它只在一个位置和屏幕中间实例化。
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; } } }
请告诉我我的脚本有什么问题。
问题是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; } }
要么
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
,您可以轻松地创建数千个对象。