【Unity3D自学记录】鼠标移动三维物体

创建一个脚本。例如以下:

using UnityEngine;
using System.Collections;

public class OnMouse : MonoBehaviour {

    IEnumerator OnMouseDown()
    {
        Vector3 screenSpace = Camera.main.WorldToScreenPoint(transform.position);//三维物体坐标转屏幕坐标
        //将鼠标屏幕坐标转为三维坐标,再算出物体位置与鼠标之间的距离
        Vector3 offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z));
        print("down");
        while (Input.GetMouseButton(0))
        {
            //print("button0");
            Vector3 curScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
            Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenSpace) + offset;
            transform.position = new Vector3(curPosition.x, transform.position.y, transform.position.z);
            yield return new WaitForFixedUpdate();//这个非常重要,循环运行
        }
    }  
}

将这个脚本赋给移动的物体就能够了

posted on 2016-01-19 20:37  gcczhongduan  阅读(207)  评论(0编辑  收藏  举报