unity3d 鼠标延各个方向拖拽物体
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了unity3d 鼠标延各个方向拖拽物体相关的知识,希望对你有一定的参考价值。
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; } } }
如果有不对,或者更好的方法,大家多多指教
以上是关于unity3d 鼠标延各个方向拖拽物体的主要内容,如果未能解决你的问题,请参考以下文章
你好,请问在UNITY3D中如何实现用鼠标左键拖拽控制一个组合物体的旋转啊?