Implementation results:
Realize:
Use Ngui to add a virtual joystick background and its sub-object buttons for buttons attach Boxcollider and Buttionscript. Add the following script for the button:
Note: The static properties can be accessed in the code that controls the movement of the object for control.
1 usingUnityengine;2 usingSystem.Collections;3 4 Public classJoystickcontrol:monobehaviour {5 6 Public Static floatH=0;7 Public Static floatv =0;8 9 Private floatParentheight;Ten Private floatParentwidth; One A Private BOOLispress=false; - - uisprite Parentspirite; the - voidAwake () - { -Parentspirite = transform.parent.getcomponent<uisprite>(); +Parentwidth =Parentspirite.width; -Parentheight =Parentspirite.height; + } A at - //Update is called once per frame - voidUpdate () { - - if(ispress) - { inVector2 Touchpos =uicamera.lasttouchposition; - toTouchpos-=NewVector2 (Parentwidth/2, Parentheight/2); + floatDistance =vector2.distance (Touchpos, Vector2.zero); - if(distance< -) the { *Transform.localposition =Touchpos; $ }Panax Notoginseng Else - { theTransform.localposition = touchpos.normalized * -; + } A theh = transform.localposition.x/ -; +v = TRANSFORM.LOCALPOSITION.Y/ -; - $ } $ Else - { -Transform.localposition =Vector2.zero; theh =0; -v =0;Wuyi } the - } Wu - voidOnpress (BOOLispress) About { $ This. ispress =ispress; - } -}
Code to control the movement of objects:
Note: The keyboard-controlled move operation is ignored when using the virtual joystick.
usingUnityengine;usingSystem.Collections; Public classMovectroller:monobehaviour {Private floatSpeed =3; //Use this for initialization voidStart () {}//Update is called once per frame voidUpdate () {floatH = Input.getaxis ("Horizontal"); floatv = Input.getaxis ("Vertical"); if(joystickcontrol.h!=0|| joystickcontrol.v!=0) {h=joyStickControl.h; V=joystickcontrol.v; } if(Mathf.abs (h) >0.3|| Mathf.abs (v) >0.3) {getcomponent<CharacterController> (). Simplemove (NewVector3 (H * speed,0, V *Speed )); } }}
Attention:
The normalized property gets the direction vector of the current vector, where
transform.localposition = touchpos.normalized *;
The range class used to keep the button in the virtual joystick background circle.
Touchpos-=new Vector2 (PARENTWIDTH/2, PARENTHEIGHT/2); to match the contact position with the Localpositon of the center button.
Implementation of virtual Stick in unity