Unity中在二维窗口中拾取和拖动三维物体的方式(最终脚本)——艾孜尔江撰
using UnityEngine;
using System.Collections;
public class MoveObj : MonoBehaviour {
private Vector3 TargetScreen; // 物体相对于屏幕的坐标
private Vector3 TargetWorld; // 物体的世界坐标
private Transform trans; //用于旋转的旋转体
private Vector3 MouseScreen; // 鼠标在屏幕上的坐标
public Transform player; //玩家的旋转体
// Use this for initialization
void Awake()
{
trans = transform;
}
IEnumerator OnMouseDown()
{
this.gameObject.GetComponent<AudioSource>().Play();//播放物体被拖动的声音
TargetScreen = Camera.main.WorldToScreenPoint(trans.position); //通过射线检测传回物体的世界坐标,转换为屏幕坐标
MouseScreen = new Vector3(Input.mousePosition.x, Input.mousePosition.y, TargetScreen.z);//通过输入计算鼠标在屏幕上的坐标
if (Vector3.Distance(this.transform.position,player.position)<3f) //计算玩家与物体的距离,距离太远无法拖动
{
while(Input.GetMouseButton(0))//按下鼠标时的方法
{
MouseScreen = new Vector3(Input.mousePosition.x, Input.mousePosition.y, TargetScreen.z);
TargetWorld = Camera.main.ScreenToWorldPoint(MouseScreen) ; //根据鼠标的移动计算出物体的世界坐标
trans.position = TargetWorld; //移动物体
yield return new WaitForFixedUpdate(); //等待下一次唤醒时的运行
}
}
}
}
该拾取方式有待优化,如有读者有更好的优化方式和建议,欢迎留言!