标签:math obj style unit upd led int star event
using UnityEngine; using System.Collections; //选择轴向 public enum directionEnum{ x_dir, y_dir, z_dir, } public class DragObject : MonoBehaviour { // Use this for initialization public directionEnum myDirection; public Transform target;//需要拖拽的目标 public bool isDrag;//表示当前是否可拖动 public float MinDistance; public float MaxDistance; private Vector3 mousePos; /// </summary> void Start () { //下面是我用NGUI的事件添加的,也可以使用UGUI或者射线检测 //UIEventListener.Get (this.gameObject).onDrag = DragTarget; //UIEventListener.Get (this.gameObject).onDragEnd = EndDrag; } // Update is called once per frame void Update () { } public void SetTarget(Transform go) { this.target = go; mousePos = Input.mousePosition;//初始化鼠标初始位置,或者放到Start函数里 } public void DragTarget() { if (isDrag) { Vector3 ScreenSpace = Camera.main.WorldToScreenPoint(target.position); //目标世界坐标转屏幕,获取z值 Vector3 curScreenSpace = new Vector3(Input.mousePosition.x,Input.mousePosition.y,ScreenSpace.z);//当前鼠标位置转世界 Vector3 offset = target.position - Camera.main.ScreenToWorldPoint (new Vector3 (mousePos.x, mousePos.y, ScreenSpace.z));//鼠标上一帧的世界位置和目标点的位置差 Vector3 CurPosition = Camera.main.ScreenToWorldPoint(curScreenSpace)+offset;//鼠标当前位置+位置差 switch (myDirection) { case directionEnum.x_dir: target.position = new Vector3 (Mathf.Clamp( CurPosition.x,MinDistance,MaxDistance), target.position.y, target.position.z); break; case directionEnum.y_dir: target.position = new Vector3 (target.position.x,Mathf.Clamp( CurPosition.y,MinDistance,MaxDistance), target.position.z); break; case directionEnum.z_dir: target.position = new Vector3 ( target.position.x, target.position.y, Mathf.Clamp( CurPosition.z,MinDistance,MaxDistance)); break; default: break; } mousePos = Input.mousePosition; } } }
如果有不对,或者更好的方法,大家多多指教
标签:math obj style unit upd led int star event
原文地址:http://www.cnblogs.com/WgBlog/p/7593819.html