Core code:
usingUnityengine;usingSystem.Collections;usingUnityengine.ui; Public Delegate voidjoystickmovedelegate (joystickdata data); Public classJoystick:monobehaviour { PublicGameobject Joystickui;//joystick Overall UI for easy active PublicRecttransform Joystickcenter;//Joystick center of gravity PublicRecttransform Joystickbackground;//Joystick Background Private floatHalfscreenwidth; Private floatHalfscreenheight; PrivateRecttransform Joystickrect; Private floatradius; PrivateVector3 lastmouseposition; Public Static Eventjoystickmovedelegate joystickmoveevent; //Use this for initialization voidStart () {halfscreenwidth= Screen.width/2; Halfscreenheight= Screen.height/2; Joystickrect= This.gameobject.getcomponent<recttransform>(); Radius= in; } //Update is called once per frame voidUpdate () {Joystickcontroller (); } Public voidJoystickcontroller () {//the mouse keeps pressing if(Input.getmousebutton (0)) { floatDistance = Vector2.distance (NewVector2 (input.mouseposition.x, INPUT.MOUSEPOSITION.Y), joystickrect.anchoredposition); if(Distance <radius) { //shift the center of gravity when the distance is less than the radiusJoystickcenter.anchoredposition =NewVector2 (input.mouseposition.x-joystickrect.anchoredposition.x, INPUT.MOUSEPOSITION.Y-JOYSTICKRECT.ANCHOREDPOSITION.Y); } Else { //find a point on a circle: (Target point-origin) * radius/distance from origin to target pointVector2 endposition = (NewVector2 (input.mouseposition.x, INPUT.MOUSEPOSITION.Y)-joystickrect.anchoredposition) * Radius/distance; Joystickcenter.anchoredposition=endposition; } if(Joystickmoveevent! =NULL) {joystickmoveevent (NewJoystickdata () {x = joystickcenter.anchoredposition.x-joystickbackground.anchoredposition.x, y = JOYSTICKCENTER.ANCHOREDPOSITION.Y-JOYSTICKBACKGROUND.ANCHOREDPOSITION.Y}); } } //mouse button down if(Input.getmousebuttondown (0)) { This. joystickui.setactive (true); //mouse click left screen if(Input.mouseposition.x <halfscreenwidth) {joystickrect.anchoredposition=input.mouseposition; } //mouse click on the right screen if(Input.mouseposition.x >=halfscreenwidth) { //Debug.Log ("Mouse Click to the Right"); } } //when the mouse is released if(Input.getmousebuttonup (0)) { This. joystickui.setactive (false); } }} Public classjoystickdata{ Public floatx; Public floaty;}
:
Unity5.1 version:
Example: HTTP://YUNPAN.CN/CCHDURTQCWXXV access password 0aba
Ugui implement rocker (imitate Tai chi panda)