测试环境:unity3d 4.6.1
1 using UnityEngine; 2 using System.Collections; 3 4 public class neccc : MonoBehaviour 5 { 6 7 8 public bool isMouseDown = false; 9 private Vector3 lastMousePosition = Vector3.zero; 10 11 Vector3 defaultPosition; 12 public float speed = 0.5f; 13 14 15 void Start() 16 { 17 lastMousePosition = Input.mousePosition; 18 19 } 20 // Update is called once per frame 21 void Update() 22 { 23 24 /* 25 * Camera.ScreenToWorldPoint 屏幕转世界位置 26 从屏幕空间到世界空间的变化位置。 27 28 屏幕空间以像素定义。屏幕的左下为(0,0);右上是(pixelWidth,pixelHeight),Z的位置是以世界单位衡量的到相机的距离。 29 */ 30 #region 鼠标移动(手机屏幕移动)鼠标或者手指不一定要在角色上 角色跟着移动 注意:这里必须2D游戏。即。在创建游戏的时候选择2D 31 if (Input.GetMouseButtonDown(0)) 32 { 33 isMouseDown = true; 34 35 } 36 if (Input.GetMouseButtonUp(0)) 37 { 38 isMouseDown = false; 39 lastMousePosition = Vector3.zero; 40 } 41 if (isMouseDown) 42 { 43 if (lastMousePosition != Vector3.zero) 44 { 45 //camera.main.ScreenToWorldPoint(Input.mousePosition); 46 Vector3 offetSet = Camera.main.ScreenToWorldPoint(Input.mousePosition) - lastMousePosition; 47 48 transform.position = transform.position + offetSet; 49 } 50 lastMousePosition = transform.position; 51 } 52 #endregion 53 54 } 55 56 57 /// <summary> 58 /// 鼠标按下,记住当前鼠标的位置(如果是手机。则是触摸的位置) 59 /// </summary> 60 void OnMouseDown() 61 { 62 defaultPosition = Input.mousePosition; 63 } 64 65 /// <summary> 66 /// 鼠标拖动(手机屏幕上拖动)移动物体 67 /// </summary> 68 void OnMouseDrag() 69 { 70 Vector3 v = Input.mousePosition - defaultPosition; 71 transform.position = v; 72 //平滑速度,根据需要用 73 //transform.position += v * Time.deltaTime * speed; 74 defaultPosition = Input.mousePosition; 75 } 76 77 }
原文:http://www.cnblogs.com/nsky/p/4593936.html