usingUnityengine;usingSystem.Collections;//Select axial Public enumdirectionenum{X_dir, Y_dir, Z_dir,} Public classDragobject:monobehaviour {//Use this for initialization PublicDirectionenum mydirection; PublicTransform Target;//Target to drag and drop Public BOOLIsdrag;//Indicates whether the current can be dragged Public floatmindistance; Public floatmaxdistance; PrivateVector3 Mousepos; /// </summary> voidStart () {//Here are some of the things I've added with Ngui, or I can use Ugui or ray detection//Uieventlistener.get (this.gameobject). Ondrag = Dragtarget; //Uieventlistener.get (this.gameobject). Ondragend = EndDrag; } //Update is called once per frame voidUpdate () {} Public voidsettarget (Transform go) { This. target =go; Mousepos= Input.mouseposition;//Initialize the initial mouse position, or put it in the start function } Public voidDragtarget () {if(Isdrag) {Vector3 screenspace= Camera.main.WorldToScreenPoint (target.position);//Target World coordinates go to screen, get Z valueVector3 Curscreenspace =NewVector3 (INPUT.MOUSEPOSITION.X,INPUT.MOUSEPOSITION.Y,SCREENSPACE.Z);//Current mouse position turn worldVector3 offset = Target.position-camera.main.screentoworldpoint (NewVector3 (Mousepos.x, Mousepos.y, screenspace.z));//The position difference between the world position and the target point of the previous frame of the mouseVector3 curposition = Camera.main.ScreenToWorldPoint (curscreenspace) +offset;//Mouse Current position + position difference Switch(mydirection) { CasedirectionEnum.x_dir:target.position=NewVector3 (Mathf.clamp (curposition.x,mindistance,maxdistance), TARGET.POSITION.Y, target.position.z); Break; CasedirectionEnum.y_dir:target.position=NewVector3 (Target.position.x,mathf.clamp (curposition.y,mindistance,maxdistance), target.position.z); Break; CasedirectionEnum.z_dir:target.position=NewVector3 (target.position.x, TARGET.POSITION.Y, Mathf.clamp (curposition.z,mindistance,maxdistance)); Break; default: Break; } Mousepos=input.mouseposition; } }}
If there is a wrong, or better way, we advise
Unity3d the mouse to drag the object in all directions