Unity3d game engine-Ios custom game joystick and plane smooth movement (11)

Source: Internet
Author: User

Unity3d game engine-Ios custom game joystick with Smooth Plane Movement

If the original Yusong Momo article is reprinted, please note: Reprinted to my independent domain name blog Yusong Momo program Research Institute, Original address: http://www.xuanyusong.com/archives/526

The touch game joystick used in mobile development games is very common on the iPhone. After all, it is a full-screen mobile phone, today, Momo uses a small example to discuss how unity3d can customize a pretty full-touch game joystick.


It is worth noting that the standard resources of the unity3d game engine have helped us encapsulate a game joystick script, so some code can be fully used by us. We need to make specific calls.


Joystick. JS is an official script. The specific code is as follows. If you are interested, you can study it carefully. Momo won't say much about it. Wow ~

//////////////////////////////////////////////////////////////// Joystick.js// Penelope iPhone Tutorial//// Joystick creates a movable joystick (via GUITexture) that // handles touch input, taps, and phases. Dead zones can control// where the joystick input gets picked up and can be normalized.//// Optionally, you can enable the touchPad property from the editor// to treat this Joystick as a TouchPad. A TouchPad allows the finger// to touch down at any point and it tracks the movement relatively // without moving the graphic//////////////////////////////////////////////////////////////@script RequireComponent( GUITexture )// A simple class for bounding how far the GUITexture will moveclass Boundary {var min : Vector2 = Vector2.zero;var max : Vector2 = Vector2.zero;}static private var joysticks : Joystick[];// A static collection of all joysticksstatic private var enumeratedJoysticks : boolean = false;static private var tapTimeDelta : float = 0.3;// Time allowed between tapsvar touchPad : boolean; // Is this a TouchPad?var touchZone : Rect;var deadZone : Vector2 = Vector2.zero;// Control when position is outputvar normalize : boolean = false; // Normalize output after the dead-zone?var position : Vector2; // [-1, 1] in x,yvar tapCount : int;// Current tap countprivate var lastFingerId = -1;// Finger last used for this joystickprivate var tapTimeWindow : float;// How much time there is left for a tap to occurprivate var fingerDownPos : Vector2;private var fingerDownTime : float;private var firstDeltaTime : float = 0.5;private var gui : GUITexture;// Joystick graphicprivate var defaultRect : Rect;// Default position / extents of the joystick graphicprivate var guiBoundary : Boundary = Boundary();// Boundary for joystick graphicprivate var guiTouchOffset : Vector2;// Offset to apply to touch inputprivate var guiCenter : Vector2;// Center of joystickfunction Start(){// Cache this component at startup instead of looking up every framegui = GetComponent( GUITexture );// Store the default rect for the gui, so we can snap back to itdefaultRect = gui.pixelInset;        defaultRect.x += transform.position.x * Screen.width;// + gui.pixelInset.x; // -  Screen.width * 0.5;    defaultRect.y += transform.position.y * Screen.height;// - Screen.height * 0.5;        transform.position.x = 0.0;    transform.position.y = 0.0;        if ( touchPad ){// If a texture has been assigned, then use the rect ferom the gui as our touchZoneif ( gui.texture )touchZone = defaultRect;}else{// This is an offset for touch input to match with the top left// corner of the GUIguiTouchOffset.x = defaultRect.width * 0.5;guiTouchOffset.y = defaultRect.height * 0.5;// Cache the center of the GUI, since it doesn't changeguiCenter.x = defaultRect.x + guiTouchOffset.x;guiCenter.y = defaultRect.y + guiTouchOffset.y;// Let's build the GUI boundary, so we can clamp joystick movementguiBoundary.min.x = defaultRect.x - guiTouchOffset.x;guiBoundary.max.x = defaultRect.x + guiTouchOffset.x;guiBoundary.min.y = defaultRect.y - guiTouchOffset.y;guiBoundary.max.y = defaultRect.y + guiTouchOffset.y;}}function Disable(){gameObject.active = false;enumeratedJoysticks = false;}function ResetJoystick(){// Release the finger control and set the joystick back to the default positiongui.pixelInset = defaultRect;lastFingerId = -1;position = Vector2.zero;fingerDownPosition = Vector2.zero;if ( touchPad )gui.color.a = 0.025;}function IsFingerDown() : boolean{return (lastFingerId != -1);}function LatchedFinger( fingerId : int ){// If another joystick has latched this finger, then we must release itif ( lastFingerId == fingerId )ResetJoystick();}function Update(){if ( !enumeratedJoysticks ){// Collect all joysticks in the game, so we can relay finger latching messagesjoysticks = FindObjectsOfType( Joystick );enumeratedJoysticks = true;}var count = Input.touchCount;// Adjust the tap time window while it still availableif ( tapTimeWindow > 0 )tapTimeWindow -= Time.deltaTime;elsetapCount = 0;if ( count == 0 )ResetJoystick();else{for(var i : int = 0;i < count; i++){var touch : Touch = Input.GetTouch(i);var guiTouchPos : Vector2 = touch.position - guiTouchOffset;var shouldLatchFinger = false;if ( touchPad ){if ( touchZone.Contains( touch.position ) )shouldLatchFinger = true;}else if ( gui.HitTest( touch.position ) ){shouldLatchFinger = true;}// Latch the finger if this is a new touchif ( shouldLatchFinger && ( lastFingerId == -1 || lastFingerId != touch.fingerId ) ){if ( touchPad ){gui.color.a = 0.15;lastFingerId = touch.fingerId;fingerDownPos = touch.position;fingerDownTime = Time.time;}lastFingerId = touch.fingerId;// Accumulate taps if it is within the time windowif ( tapTimeWindow > 0 )tapCount++;else{tapCount = 1;tapTimeWindow = tapTimeDelta;}// Tell other joysticks we've latched this fingerfor ( var j : Joystick in joysticks ){if ( j != this )j.LatchedFinger( touch.fingerId );}}if ( lastFingerId == touch.fingerId ){// Override the tap count with what the iPhone SDK reports if it is greater// This is a workaround, since the iPhone SDK does not currently track taps// for multiple touchesif ( touch.tapCount > tapCount )tapCount = touch.tapCount;if ( touchPad ){// For a touchpad, let's just set the position directly based on distance from initial touchdownposition.x = Mathf.Clamp( ( touch.position.x - fingerDownPos.x ) / ( touchZone.width / 2 ), -1, 1 );position.y = Mathf.Clamp( ( touch.position.y - fingerDownPos.y ) / ( touchZone.height / 2 ), -1, 1 );}else{// Change the location of the joystick graphic to match where the touch isgui.pixelInset.x =  Mathf.Clamp( guiTouchPos.x, guiBoundary.min.x, guiBoundary.max.x );gui.pixelInset.y =  Mathf.Clamp( guiTouchPos.y, guiBoundary.min.y, guiBoundary.max.y );}if ( touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled )ResetJoystick();}}}if ( !touchPad ){// Get a value between -1 and 1 based on the joystick graphic locationposition.x = ( gui.pixelInset.x + guiTouchOffset.x - guiCenter.x ) / guiTouchOffset.x;position.y = ( gui.pixelInset.y + guiTouchOffset.y - guiCenter.y ) / guiTouchOffset.y;}// Adjust for dead zonevar absoluteX = Mathf.Abs( position.x );var absoluteY = Mathf.Abs( position.y );if ( absoluteX < deadZone.x ){// Report the joystick as being at the center if it is within the dead zoneposition.x = 0;}else if ( normalize ){// Rescale the output after taking the dead zone into accountposition.x = Mathf.Sign( position.x ) * ( absoluteX - deadZone.x ) / ( 1 - deadZone.x );}if ( absoluteY < deadZone.y ){// Report the joystick as being at the center if it is within the dead zoneposition.y = 0;}else if ( normalize ){// Rescale the output after taking the dead zone into accountposition.y = Mathf.Sign( position.y ) * ( absoluteY - deadZone.y ) / ( 1 - deadZone.y );}}

Click Create to create a GUI texture named Joy, which is used to display the game joystick. As shown in, the joystick image resource is assigned to joy by connecting with the joystick script. you can set the display position and width and height of the joystick in pixel inset.

At this step of building and run, you can see the game joystick on the iPhone, and you can touch it, 360 degrees smooth and excessive.

Draw an airplane on the screen and use the game joystick to control the movement of the airplane.


Create a script named main. js and bind main. JS, joy, and plan to main camera respectively.






Movejoystick. position. X;

Movejoystick. position. Y;


These two values are two very important information. Their values range from-1 to + 1, indicating the position of the user to touch the joystick and the information from top to bottom to right.


// Game joystick object var movejoystick: joystick; // plane texture var plan: texture; // coordinates of the plane on the screen var x = 0; var y = 0; // prevent the plane from flying out of the screen. The maximum coordinates are X and Y. The minimum coordinates are 0 and 0var cross_x = 0. var cross_y = 0; // The speed of airplane movement var planspeed = 20; function start () {// The initial value is X = 100; y = 100; cross_x = screen. width-plan. width; cross_y = screen. height-plan. height;} function Update () {// obtain the feedback from the game joystick. The obtained value is-1 to + 1 var touchkey_x = movejoystick. position. x; var touchkey_y = movejoystick. position. y; // The joystick to the left if (touchkey_x =-1) {X-= planspeed;} // The joystick to the right else if (touchkey_x = 1) {x + = planspeed;} // joystick up if (touchkey_y =-1) {Y + = planspeed;} // joystick down else if (touchkey_y = 1) {Y-= planspeed;} // prevents planes from flying out of the screen. If (x <0) {x = 0;} else if (x> cross_x) {x = cross_x;} If (Y <0) {Y = 0;} else if (Y> cross_y) {Y = cross_y;} function ongui () {// draw the plane to the GUI on the screen. drawtexture (rect (X, Y, 128,128), Plan );}

Export the build and run command to check the effects on the iPhone. You can touch the game joystick to control the movements of the plane ~~

Finally, you are welcome to discuss unity3d game development with Momo. More and more friends have caught a cold recently. Please pay more attention to your health. Wow ~~~ Attached to the unity3d project, I will not upload the xcode project and export it by myself.

:Http://www.xuanyusong.com/archives/526

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.