先看演示效果
实现方案
1.创建几个用于演示的Cube
2.创建一个脚本
3.编写脚本的内容
附上代码片段
float distance;
// Update is called once per frame
void Update()
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Input.GetMouseButtonDown(0))
{
if (Physics.Raycast(ray, out hit))
{
distance = Vector3.Distance(hit.transform.position, Camera.main.transform.position);
}
}
if (Input.GetMouseButton(0))
{
if (Physics.Raycast(ray, out hit))
{
if (hit.collider != null)
{
var mousePoint = Input.mousePosition;
mousePoint.z = distance;
hit.collider.gameObject.transform.position = Camera.main.ScreenToWorldPoint(mousePoint);
}
}
}
}
4.挂载脚本
5.点击运行就可以看到效果啦