First, create a virtual joystick map with Ngui
First create a sprite as the background called joystick and add a boxcollider, and then create a sprite child as the middle of the virtual Joystick button, called button
Second, the X, Y offset value is obtained through the virtual joystick.
1 usingUnityengine;2 usingSystem.Collections;3 4 Public classJoystick:monobehaviour5 {6 7 Private BOOLIspress =false;8 PrivateTransform button;9 Ten //x, y offset from virtual joystick-between 1 and 1 One Public Static floath =0; A Public Static floatv =0; - voidAwake () - { theButton = transform. Findchild ("Button"); - } - voidOnpress (BOOLispress) - { + This. ispress =ispress; - if(!ispress) + { AButton.localposition =Vector2.zero; ath =0; -v =0; - } - } - - voidUpdate () in { - if(ispress) to { +Vector2 Touchpos = uicamera.lasteventposition-NewVector2 ( the, the); - floatDistance =vector2.distance (Vector2.zero, touchpos); the if(Distance > the)//Virtual Joystick button cannot exceed radius * { $Touchpos = touchpos.normalized * the;Panax Notoginseng } -Button.localposition =Touchpos; the +h = touchpos.x/ the; Av = touchpos.y/ the; the } + } -}
Third, the character controller has been added by moving the protagonist through the migration control
1 usingUnityengine;2 usingSystem.Collections;3 4 Public classPlayermove:monobehaviour5 {6 PrivateCharactercontroller cc;7 Public floatSpeed =3f;8 9 voidAwake ()Ten { OneCC = getcomponent<charactercontroller>(); A } - - //Update is called once per frame the voidUpdate () - { - //Keyboard Control - floatH = Input.getaxis ("Horizontal"); + floatv = Input.getaxis ("Vertical"); - + //Virtual Joystick Control A if(JoyStick.h! =0|| JOYSTICK.V! =0) at { -h =JoyStick.h; -v =joystick.v; - } - - if(Mathf.abs (h) >0.1f|| Mathf.abs (v) >0.1f) in { -Vector3 TargetDir =NewVector3 (H,0, v); toTransform. LookAt (TargetDir +transform.position); +Acl Simplemove (TargetDir *Speed ); - } the * $ }Panax Notoginseng}
Simple virtual joystick Control movement (NGUI)