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();//这个很重要,循环执行
 }
 } 
}

 

未经允许不得转载:第一Unity3D » Unity3D浅析鼠标移动三维物体的示例

赞 (0)