Search Unity

VJR (Virtual Joystick Region) Sample

Discussion in 'iOS and tvOS' started by BrUnO-XaVIeR, Dec 19, 2011.

  1. BrUnO-XaVIeR

    BrUnO-XaVIeR

    Joined:
    Dec 6, 2010
    Posts:
    1,687
    Hello!
    For many times people come around asking on how to make a virtual joystick for iOS/Android and most of the time I see they are frustrated by the Penelope's sample; so Im giving this away for those who still in trouble trying to find an easy to use VJR:

    (Inactive):


    (Active):


    It solves many problems you face when trying to code a joystick, so if you are learning about it you may want to take a look. Also it is somewhat resolution independant so you dont have to worry about adjusting its size neither position.
    This sample works within a "region" of the screen where the joystick adjusts its position to the player's finger if he taps inside that region.
    It also work inside a circular boundary instead of a square and it can detect double taps too.
    It does not use OnGUI(), its GUItextures and it does not need collision detection to work; very simple to use:

    1) Create an empty Game Object. Make sure its transform is at (0,0,0).
    2) Add the VirtualJoystickRegion.cs script to that object.
    3) Use square textures for the "Joytick 2D" and "Background 2D" fields.
    4) Adjust the "Active Color" and "Inactive Color" values as you wish, and its ready to go.

    Note:
    The Joystick outputs two global variables for you to work with, VJRvector and VJRnormals.
    To get real screen space values, you query "VirtualJoystickRegion.VJRvector".
    To get normalized joystick values, ideal numbers to work with, you query "VirtualJoystickRegion.VJRnormals".
    If you dont like big names you may want to rename the "VirtualJoystickRegion" class to just "VJR".

    Have fun!
    Code (csharp):
    1.  
    2. using UnityEngine;
    3.  
    4. public class VirtualJoystickRegion : MonoBehaviour {
    5.     public static Vector2 VJRvector;    // Joystick's controls in Screen-Space.
    6.     public static Vector2 VJRnormals;   // Joystick's normalized controls.
    7.     public static bool VJRdoubleTap;    // Player double tapped this Joystick.
    8.     public Color activeColor;           // Joystick's color when active.
    9.     public Color inactiveColor;         // Joystick's color when inactive.
    10.     public Texture2D joystick2D;        // Joystick's Image.
    11.     public Texture2D background2D;      // Background's Image.
    12.     private GameObject backOBJ;         // Background's Object.
    13.     private GUITexture joystick;        // Joystick's GUI.
    14.     private GUITexture background;      // Background's GUI.
    15.     private Vector2 origin;             // Touch's Origin in Screen-Space.
    16.     private Vector2 position;           // Pixel Position in Screen-Space.
    17.     private int size;                   // Screen's smaller side.
    18.     private float length;               // The maximum distance the Joystick can be pushed.
    19.     private bool gotPosition;           // Joystick has a position.
    20.     private int fingerID;               // ID of finger touching this Joystick.
    21.     private int lastID;                 // ID of last finger touching this Joystick.
    22.     private float tapTimer;             // Double-tap's timer.
    23.     private bool enable;                // VJR external control.
    24.    
    25.     //
    26.    
    27.     public void DisableJoystick() {enable = false; ResetJoystick();}
    28.     public void EnableJoystick() {enable = true; ResetJoystick();}
    29.    
    30.     //
    31.  
    32.     private void ResetJoystick() {
    33.         VJRvector = new Vector2(0,0); VJRnormals = VJRvector;
    34.         lastID = fingerID; fingerID = -1; tapTimer = 0.150f;
    35.         joystick.color = inactiveColor; position = origin; gotPosition = false;
    36.     }
    37.  
    38.     private Vector2 GetRadius(Vector2 midPoint, Vector2 endPoint, float maxDistance) {
    39.         Vector2 distance = endPoint;
    40.         if (Vector2.Distance(midPoint,endPoint) > maxDistance) {
    41.             distance = endPoint-midPoint; distance.Normalize();
    42.             return (distance*maxDistance)+midPoint;
    43.         }
    44.         return distance;
    45.     }
    46.  
    47.     private void GetPosition() {
    48.         foreach (Touch touch in Input.touches) {
    49.             fingerID = touch.fingerId;
    50.             if (fingerID >= 0  fingerID < Input.touchCount) {
    51.                 if(Input.GetTouch(fingerID).position.x < Screen.width/3  Input.GetTouch(fingerID).position.y < Screen.height/3  Input.GetTouch(fingerID).phase == TouchPhase.Began) {
    52.                     position = Input.GetTouch(fingerID).position; origin = position;
    53.                     joystick.texture = joystick2D; joystick.color = activeColor;
    54.                     background.texture = background2D; background.color = activeColor;
    55.                     if (fingerID == lastID  tapTimer > 0) {VJRdoubleTap = true;} gotPosition = true;
    56.                 }
    57.             }
    58.         }
    59.     }
    60.  
    61.     private void GetConstraints() {
    62.         if (origin.x < (background.pixelInset.width/2)+25) {origin.x = (background.pixelInset.width/2)+25;}
    63.         if (origin.y < (background.pixelInset.height/2)+25) {origin.y = (background.pixelInset.height/2)+25;}
    64.         if (origin.x > Screen.width/3) {origin.x = Screen.width/3;}
    65.         if (origin.y > Screen.height/3) {origin.y = Screen.height/3;}
    66.     }
    67.    
    68.     private Vector2 GetControls(Vector2 pos, Vector2 ori) {
    69.         Vector2 vector = new Vector2();
    70.         if (Vector2.Distance(pos,ori) > 0) {vector = new Vector2(pos.x-ori.x,pos.y-ori.y);}
    71.         return vector;
    72.     }
    73.  
    74.     //
    75.    
    76.     private void Awake() {
    77.         gameObject.transform.localScale = new Vector3(0,0,0);
    78.         gameObject.transform.position = new Vector3(0,0,999);
    79.         if (Screen.width > Screen.height) {size = Screen.height;} else {size = Screen.width;} VJRvector = new Vector2(0,0);
    80.         joystick = gameObject.AddComponent("GUITexture") as GUITexture;
    81.         joystick.texture = joystick2D; joystick.color = inactiveColor;
    82.         backOBJ = new GameObject("VJR-Joystick Back");
    83.         backOBJ.transform.localScale = new Vector3(0,0,0);
    84.         background = backOBJ.AddComponent("GUITexture") as GUITexture;
    85.         background.texture = background2D; background.color = inactiveColor;
    86.         fingerID = -1; lastID = -1; VJRdoubleTap = false; tapTimer = 0; length = 50;
    87.         position = new Vector2((Screen.width/3)/2,(Screen.height/3)/2); origin = position;
    88.         gotPosition = false; EnableJoystick(); enable = true;
    89.     }
    90.    
    91.     private void Update() {
    92.         if (tapTimer > 0) {tapTimer -= Time.deltaTime;}
    93.         if (fingerID > -1  fingerID >= Input.touchCount) {ResetJoystick();}
    94.         if (enable == true) {
    95.             if (Input.touchCount > 0  gotPosition == false) {GetPosition(); GetConstraints();}
    96.             if (Input.touchCount > 0  fingerID > -1  fingerID < Input.touchCount  gotPosition == true) {
    97.                 foreach (Touch touch in Input.touches) {
    98.                     if (touch.fingerId == fingerID) {
    99.                         position = touch.position; position = GetRadius(origin,position,length);
    100.                         VJRvector = GetControls(position,origin); VJRnormals = new Vector2(VJRvector.x/length,VJRvector.y/length);
    101.                         if (Input.GetTouch(fingerID).position.x > (Screen.width/3)+background.pixelInset.width
    102.                         || Input.GetTouch(fingerID).position.y > (Screen.height/3)+background.pixelInset.height) {ResetJoystick();}
    103.                         //
    104.                         Debug.Log("Joystick Axis:: "+VJRnormals); //<-- Delete this line | (X,Y), from -1.0 to +1.0 | Use this value "VJRnormals" in your scripts.
    105.                     }
    106.                 }
    107.             }
    108.             if (gotPosition == true  Input.touchCount > 0  fingerID > -1  fingerID < Input.touchCount) {
    109.                 if (Input.GetTouch(fingerID).phase == TouchPhase.Ended || Input.GetTouch(fingerID).phase == TouchPhase.Canceled) {ResetJoystick();}
    110.             }
    111.             if (gotPosition == false  fingerID == -1  tapTimer <= 0) {if (background.color != inactiveColor) {background.color = inactiveColor;}}
    112.             background.pixelInset = new Rect(origin.x-(background.pixelInset.width/2),origin.y-(background.pixelInset.height/2),size/5,size/5);
    113.             joystick.pixelInset = new Rect(position.x-(joystick.pixelInset.width/2),position.y-(joystick.pixelInset.height/2),size/11,size/11);
    114.         } else if (background.pixelInset.width > 0) {background.pixelInset = new Rect(0,0,0,0); joystick.pixelInset = new Rect(0,0,0,0);}
    115.     }
    116. }
    117.  
     

    Attached Files:

    Last edited: Sep 5, 2012
  2. Filax

    Filax

    Guest

    Joined:
    Mar 30, 2011
    Posts:
    8
    Hard to find, but thank to share !
     
  3. BrUnO-XaVIeR

    BrUnO-XaVIeR

    Joined:
    Dec 6, 2010
    Posts:
    1,687
    Yes, I may put a link under my signature, but still I have not THAT many posts to spread it out :)
    You're welcome, have fun with it.
     
  4. dhondon

    dhondon

    Joined:
    Oct 16, 2010
    Posts:
    55
    Thank you for sharing this:)
     
    britz033 likes this.
  5. BrUnO-XaVIeR

    BrUnO-XaVIeR

    Joined:
    Dec 6, 2010
    Posts:
    1,687
    You're welcome ;)
     
  6. kenshin

    kenshin

    Joined:
    Apr 21, 2010
    Posts:
    940
    Thank's for sharing, is very very useful!
     
  7. BrUnO-XaVIeR

    BrUnO-XaVIeR

    Joined:
    Dec 6, 2010
    Posts:
    1,687
    I'm happy for it being useful ;)
    Have fun.
     
  8. web76

    web76

    Joined:
    Nov 4, 2009
    Posts:
    150
    Hi, and thanks, is it possible to get this working with mouse input also, for standalone build?

    Kind Regards
    Web
     
    Last edited: Jan 23, 2012
  9. BrUnO-XaVIeR

    BrUnO-XaVIeR

    Joined:
    Dec 6, 2010
    Posts:
    1,687
    Why would you need a virtual joystick on screen for a non-portable device? I dont get it.
    Unity has mouse api already.
     
    Toucansam likes this.
  10. web76

    web76

    Joined:
    Nov 4, 2009
    Posts:
    150
    I am having trouble getting the mouse to mimic an onscreen joystick, I want to visualize and animate the joystick on screen, we have a physical panel w/joystick in hardware, and I want to reproduce that onscreen, for additional control..
     
  11. BrUnO-XaVIeR

    BrUnO-XaVIeR

    Joined:
    Dec 6, 2010
    Posts:
    1,687
    I think it is possible to re-create it using mouse position instead of touch, but I didnt try it.
     
  12. web76

    web76

    Joined:
    Nov 4, 2009
    Posts:
    150
    Got it working with the standard mobile joystick now! Thanks anyway.
     
  13. Dreeka

    Dreeka

    Joined:
    Jul 15, 2010
    Posts:
    507
    Is it possible to change the size of the joystick? It is too small on my screen.
     
  14. marjan

    marjan

    Joined:
    Jun 6, 2009
    Posts:
    563
    I did something like this for NGUI. Means, it doesn´t use UITextures, but NGUI Sprites instead.

    You can find it here:

    PS, this one also works with mouse.
     
  15. Dreeka

    Dreeka

    Joined:
    Jul 15, 2010
    Posts:
    507
    That looks good marjan!
    Too bad I dont have NGUI.
     
  16. BrUnO-XaVIeR

    BrUnO-XaVIeR

    Joined:
    Dec 6, 2010
    Posts:
    1,687
    This script is just an example, you can modify it as you wish, I'll expose variables for you to control graphic size so you can take a close look on it.

    Edit: Ok, here you go...
    Code (csharp):
    1.  
    2. using UnityEngine;
    3.  
    4. public class VirtualJoystickRegion : MonoBehaviour {
    5.     public static Vector2 VJRvector;    // Joystick's controls in Screen-Space.
    6.     public static Vector2 VJRnormals;   // Joystick's normalized controls.
    7.     public static bool VJRdoubleTap;    // Player double tapped this Joystick.
    8.     public Color activeColor;           // Joystick's color when active.
    9.     public Color inactiveColor;         // Joystick's color when inactive.
    10.     public Texture2D joystick2D;        // Joystick's Image.
    11.     public Texture2D background2D;      // Background's Image.
    12.     public bool useAbsoluteScales;      // If true, graphics wont auto-scale.
    13.     public int[] joystickScale;         // Size of joystick in pixels, if using absolute scales.
    14.     public int[] backgroundScale;       // Size of background in pixels, if using absolute scales.
    15.     private GameObject backOBJ;         // Background's Object.
    16.     private GUITexture joystick;        // Joystick's GUI.
    17.     private GUITexture background;      // Background's GUI.
    18.     private Vector2 origin;             // Touch's Origin in Screen-Space.
    19.     private Vector2 position;           // Pixel Position in Screen-Space.
    20.     private int size;                   // Screen's smaller side.
    21.     private float length;               // The maximum distance the Joystick can be pushed.
    22.     private bool gotPosition;           // Joystick has a position.
    23.     private int fingerID;               // ID of finger touching this Joystick.
    24.     private int lastID;                 // ID of last finger touching this Joystick.
    25.     private float tapTimer;             // Double-tap's timer.
    26.     private bool enable;                // VJR external control.
    27.    
    28.     //
    29.    
    30.     public void DisableJoystick() {enable = false; ResetJoystick();}
    31.     public void EnableJoystick() {enable = true; ResetJoystick();}
    32.    
    33.     //
    34.  
    35.     private void ResetJoystick() {
    36.         VJRvector = new Vector2(0,0); VJRnormals = VJRvector;
    37.         lastID = fingerID; fingerID = -1; tapTimer = 0.150f;
    38.         joystick.color = inactiveColor; position = origin; gotPosition = false;
    39.     }
    40.  
    41.     private Vector2 GetRadius(Vector2 midPoint, Vector2 endPoint, float maxDistance) {
    42.         Vector2 distance = endPoint;
    43.         if (Vector2.Distance(midPoint,endPoint) > maxDistance) {
    44.             distance = endPoint-midPoint; distance.Normalize();
    45.             return (distance*maxDistance)+midPoint;
    46.         }
    47.         return distance;
    48.     }
    49.  
    50.     private void GetPosition() {
    51.         foreach (Touch touch in Input.touches) {
    52.             fingerID = touch.fingerId;
    53.             if (fingerID >= 0  fingerID < Input.touchCount) {
    54.                 if(Input.GetTouch(fingerID).position.x < Screen.width/3  Input.GetTouch(fingerID).position.y < Screen.height/3  Input.GetTouch(fingerID).phase == TouchPhase.Began) {
    55.                     position = Input.GetTouch(fingerID).position; origin = position;
    56.                     joystick.texture = joystick2D; joystick.color = activeColor;
    57.                     background.texture = background2D; background.color = activeColor;
    58.                     if (fingerID == lastID  tapTimer > 0) {VJRdoubleTap = true;} gotPosition = true;
    59.                 }
    60.             }
    61.         }
    62.     }
    63.  
    64.     private void GetConstraints() {
    65.         if (origin.x < (background.pixelInset.width/2)+25) {origin.x = (background.pixelInset.width/2)+25;}
    66.         if (origin.y < (background.pixelInset.height/2)+25) {origin.y = (background.pixelInset.height/2)+25;}
    67.         if (origin.x > Screen.width/3) {origin.x = Screen.width/3;}
    68.         if (origin.y > Screen.height/3) {origin.y = Screen.height/3;}
    69.     }
    70.    
    71.     private Vector2 GetControls(Vector2 pos, Vector2 ori) {
    72.         Vector2 vector = new Vector2();
    73.         if (Vector2.Distance(pos,ori) > 0) {vector = new Vector2(pos.x-ori.x,pos.y-ori.y);}
    74.         return vector;
    75.     }
    76.  
    77.     //
    78.  
    79.     private void Awake() {
    80.         gameObject.transform.localScale = new Vector3(0,0,0);
    81.         gameObject.transform.position = new Vector3(0,0,999);
    82.         if (Screen.width > Screen.height) {size = Screen.height;} else {size = Screen.width;} VJRvector = new Vector2(0,0);
    83.         joystick = gameObject.AddComponent("GUITexture") as GUITexture;
    84.         joystick.texture = joystick2D; joystick.color = inactiveColor;
    85.         backOBJ = new GameObject("VJR-Joystick Back");
    86.         backOBJ.transform.localScale = new Vector3(0,0,0);
    87.         background = backOBJ.AddComponent("GUITexture") as GUITexture;
    88.         background.texture = background2D; background.color = inactiveColor;
    89.         fingerID = -1; lastID = -1; VJRdoubleTap = false; tapTimer = 0; length = 50;
    90.         position = new Vector2((Screen.width/3)/2,(Screen.height/3)/2); origin = position;
    91.         gotPosition = false; EnableJoystick(); enable = true;
    92.     }
    93.    
    94.     private void Update() {
    95.         if (tapTimer > 0) {tapTimer -= Time.deltaTime;}
    96.         if (fingerID > -1  fingerID >= Input.touchCount) {ResetJoystick();}
    97.         if (enable == true) {
    98.             if (Input.touchCount > 0  gotPosition == false) {GetPosition(); GetConstraints();}
    99.             if (Input.touchCount > 0  fingerID > -1  fingerID < Input.touchCount  gotPosition == true) {
    100.                 foreach (Touch touch in Input.touches) {
    101.                     if (touch.fingerId == fingerID) {
    102.                         position = touch.position; position = GetRadius(origin,position,length);
    103.                         VJRvector = GetControls(position,origin); VJRnormals = new Vector2(VJRvector.x/length,VJRvector.y/length);
    104.                         if (Input.GetTouch(fingerID).position.x > (Screen.width/3)+background.pixelInset.width
    105.                         || Input.GetTouch(fingerID).position.y > (Screen.height/3)+background.pixelInset.height) {ResetJoystick();}
    106.                         //
    107.                         Debug.Log("Joystick Axis:: "+VJRnormals); //<-- Delete this line | (X,Y), from -1.0 to +1.0 | Use this value "VJRnormals" in your scripts.
    108.                     }
    109.                 }
    110.             }
    111.             if (gotPosition == true  Input.touchCount > 0  fingerID > -1  fingerID < Input.touchCount) {
    112.                 if (Input.GetTouch(fingerID).phase == TouchPhase.Ended || Input.GetTouch(fingerID).phase == TouchPhase.Canceled) {ResetJoystick();}
    113.             }
    114.             if (gotPosition == false  fingerID == -1  tapTimer <= 0) {if (background.color != inactiveColor) {background.color = inactiveColor;}}
    115.             //
    116.             if (useAbsoluteScales) {
    117.                 if (joystickScale.Length < 2) {Debug.LogError(this.name+"(JVR): "+"Did you setup 'X,Y' absolute scales for the joystick? Set 'Size' = 2..."); return;}
    118.                 if (backgroundScale.Length < 2) {Debug.LogError(this.name+"(JVR): "+"Did you setup 'X,Y' absolute scales for the background? Set 'Size' = 2..."); return;}
    119.                 background.pixelInset = new Rect(origin.x-(background.pixelInset.width/2),origin.y-(background.pixelInset.height/2),backgroundScale[0],backgroundScale[1]);
    120.                 joystick.pixelInset = new Rect(position.x-(joystick.pixelInset.width/2),position.y-(joystick.pixelInset.height/2),joystickScale[0],joystickScale[1]);
    121.             } else {
    122.                 background.pixelInset = new Rect(origin.x-(background.pixelInset.width/2),origin.y-(background.pixelInset.height/2),size/5,size/5);
    123.                 joystick.pixelInset = new Rect(position.x-(joystick.pixelInset.width/2),position.y-(joystick.pixelInset.height/2),size/11,size/11);
    124.             }
    125.         } else if (background.pixelInset.width > 0) {background.pixelInset = new Rect(0,0,0,0); joystick.pixelInset = new Rect(0,0,0,0);}
    126.     }
    127. }
    128.  
    Those change the graphics size on screen if you turn on "useAbsoluteScales".
    You also have to set up a value for X and Y(index 0 and 1) for "joystickScale" and "backgroundScale" arrays.
     
    Last edited: Feb 28, 2012
  17. vdek

    vdek

    Joined:
    Sep 2, 2011
    Posts:
    368
    It's pretty neat, it needs some modifying though to work as a twin stick :p

    Thanks for sharing!
     
  18. BrUnO-XaVIeR

    BrUnO-XaVIeR

    Joined:
    Dec 6, 2010
    Posts:
    1,687
    Yes, I've never done anything using twin sticks so I didnt build this thinking about it.
     
  19. dasbin

    dasbin

    Joined:
    Jan 14, 2012
    Posts:
    261
    Thanks so much for this.

    For some reason the GUITexture is not rendering for me. I don't know why. The component appears when run, but nothing shows up on the screen. I know the joystick is there because I can press in the lower-left and it works. Other GUITextures in my scene *do* render properly, just this one for some reason does not appear.
    Any ideas?
     
  20. BrUnO-XaVIeR

    BrUnO-XaVIeR

    Joined:
    Dec 6, 2010
    Posts:
    1,687
    Make sure you are editing the colors for your textures. If you leave it all black, (null when you attach the script) the textures are not rendered.
     
  21. dasbin

    dasbin

    Joined:
    Jan 14, 2012
    Posts:
    261
    That doesn't seem to be it.

    Might this require Unity Pro for some reason?
     
  22. BrUnO-XaVIeR

    BrUnO-XaVIeR

    Joined:
    Dec 6, 2010
    Posts:
    1,687
    No, it just requires GUItextures.
    Send me a sample scene and I take a look to see whats going on, please.
     
  23. jackson31

    jackson31

    Joined:
    Aug 25, 2010
    Posts:
    28
    Thanks so much for sharing this Bruno! :D
    It's a really neat script
     
  24. ColeBKray

    ColeBKray

    Joined:
    Dec 18, 2011
    Posts:
    36
    I have the same problem here, no textures appear, and I've changed the colors. What can be wrong?
     
  25. Dreeka

    Dreeka

    Joined:
    Jul 15, 2010
    Posts:
    507
    Hey,

    I need a static version from this joystick, so it does not move to the touch position.
    I have tried to create it, but it has two issues.

    When the level starts, it does not appear on the proper position, but jumps to it later, when the screen has been touched.

    Secondly, when I click under, or to the left of the joystick, it the joystick register it, but when I click above, or to the right, it does not.

    Here is my modified version:

    Code (csharp):
    1.  
    2.  
    3. using UnityEngine;
    4.      
    5.     public class VirtualJoystickRegion : MonoBehaviour {
    6.         public static Vector2 VJRvector;    // Joystick's controls in Screen-Space.
    7.         public static Vector2 VJRnormals;   // Joystick's normalized controls.
    8.         public static bool VJRdoubleTap;    // Player double tapped this Joystick.
    9.         public Color activeColor;           // Joystick's color when active.
    10.         public Color inactiveColor;         // Joystick's color when inactive.
    11.         public Texture2D joystick2D;        // Joystick's Image.
    12.         public Texture2D background2D;      // Background's Image.
    13.         public bool useAbsoluteScales;      // If true, graphics wont auto-scale.
    14.         public int[] joystickScale;         // Size of joystick in pixels, if using absolute scales.
    15.         public int[] backgroundScale;       // Size of background in pixels, if using absolute scales.
    16.         public bool isLocked = false;       // Joystick position is locked
    17.         private GameObject backOBJ;         // Background's Object.
    18.         private GUITexture joystick;        // Joystick's GUI.
    19.         private GUITexture background;      // Background's GUI.
    20.         private Vector2 origin;             // Touch's Origin in Screen-Space.
    21.         private Vector2 position;           // Pixel Position in Screen-Space.
    22.         private int size;                   // Screen's smaller side.
    23.         private float length;               // The maximum distance the Joystick can be pushed.
    24.         private bool gotPosition;           // Joystick has a position.
    25.         private int fingerID;               // ID of finger touching this Joystick.
    26.         private int lastID;                 // ID of last finger touching this Joystick.
    27.         private float tapTimer;             // Double-tap's timer.
    28.         private bool enable;                // VJR external control.
    29.        
    30.         //
    31.        
    32.         public void DisableJoystick() {enable = false; ResetJoystick();}
    33.         public void EnableJoystick() {enable = true; ResetJoystick();}
    34.        
    35.         //
    36.      
    37.         private void ResetJoystick() {
    38.             VJRvector = new Vector2(0,0); VJRnormals = VJRvector;
    39.             lastID = fingerID; fingerID = -1; tapTimer = 0.150f;
    40.             joystick.color = inactiveColor; position = origin; gotPosition = false;
    41.         }
    42.      
    43.         private Vector2 GetRadius(Vector2 midPoint, Vector2 endPoint, float maxDistance) {
    44.             Vector2 distance = endPoint;
    45.             if (Vector2.Distance(midPoint,endPoint) > maxDistance) {
    46.                 distance = endPoint-midPoint; distance.Normalize();
    47.                 return (distance*maxDistance)+midPoint;
    48.             }
    49.             return distance;
    50.         }
    51.      
    52.         private void GetPosition() {
    53.             foreach (Touch touch in Input.touches) {
    54.                 fingerID = touch.fingerId;
    55.                 if (fingerID >= 0  fingerID < Input.touchCount) {
    56.                     if(Input.GetTouch(fingerID).position.x < Screen.width/3  Input.GetTouch(fingerID).position.y < Screen.height/3  Input.GetTouch(fingerID).phase == TouchPhase.Began) {
    57.                         if (!isLocked)
    58.                             position = Input.GetTouch (fingerID).position;
    59.                         else
    60.                             position = new Vector2 ((Screen.width / 3) / 2, (Screen.height / 3) / 2);
    61.                         joystick.texture = joystick2D; joystick.color = activeColor;
    62.                         background.texture = background2D; background.color = activeColor;
    63.                         if (fingerID == lastID  tapTimer > 0) {VJRdoubleTap = true;} gotPosition = true;
    64.                     }
    65.                 }
    66.             }
    67.         }
    68.      
    69.         private void GetConstraints() {
    70.             if (origin.x < (background.pixelInset.width/2)+25) {origin.x = (background.pixelInset.width/2)+25;}
    71.             if (origin.y < (background.pixelInset.height/2)+25) {origin.y = (background.pixelInset.height/2)+25;}
    72.             if (origin.x > Screen.width/3) {origin.x = Screen.width/3;}
    73.             if (origin.y > Screen.height/3) {origin.y = Screen.height/3;}
    74.         }
    75.        
    76.         private Vector2 GetControls(Vector2 pos, Vector2 ori) {
    77.             Vector2 vector = new Vector2();
    78.             if (Vector2.Distance(pos,ori) > 0) {vector = new Vector2(pos.x-ori.x,pos.y-ori.y);}
    79.             return vector;
    80.         }
    81.      
    82.         //
    83.      
    84.         private void Awake() {
    85.             gameObject.transform.localScale = new Vector3(0,0,0);
    86.             gameObject.transform.position = new Vector3(0,0,999);
    87.             if (Screen.width > Screen.height) {size = Screen.height;} else {size = Screen.width;} VJRvector = new Vector2(0,0);
    88.             joystick = gameObject.AddComponent("GUITexture") as GUITexture;
    89.             joystick.texture = joystick2D; joystick.color = inactiveColor;
    90.             backOBJ = new GameObject("VJR-Joystick Back");
    91.             backOBJ.transform.localScale = new Vector3(0,0,0);
    92.             background = backOBJ.AddComponent("GUITexture") as GUITexture;
    93.             background.texture = background2D; background.color = inactiveColor;
    94.             fingerID = -1; lastID = -1; VJRdoubleTap = false; tapTimer = 0; length = 50;
    95.             position = new Vector2((Screen.width/3)/2,(Screen.height/3)/2); origin = position;
    96.             gotPosition = false; EnableJoystick(); enable = true;
    97.         }
    98.        
    99.         private void Update() {
    100.             if (tapTimer > 0) {tapTimer -= Time.deltaTime;}
    101.             if (fingerID > -1  fingerID >= Input.touchCount) {ResetJoystick();}
    102.             if (enable == true) {
    103.                 if (Input.touchCount > 0  gotPosition == false) {GetPosition(); GetConstraints();}
    104.                 if (Input.touchCount > 0  fingerID > -1  fingerID < Input.touchCount  gotPosition == true) {
    105.                     foreach (Touch touch in Input.touches) {
    106.                         if (touch.fingerId == fingerID) {
    107.                             position = touch.position; position = GetRadius(origin,position,length);
    108.                             VJRvector = GetControls(position,origin); VJRnormals = new Vector2(VJRvector.x/length,VJRvector.y/length);
    109.                             if (Input.GetTouch(fingerID).position.x > (Screen.width/3)+background.pixelInset.width
    110.                             || Input.GetTouch(fingerID).position.y > (Screen.height/3)+background.pixelInset.height) {ResetJoystick();}
    111.                             //
    112.                             Debug.Log("Joystick Axis:: "+VJRnormals); //<-- Delete this line | (X,Y), from -1.0 to +1.0 | Use this value "VJRnormals" in your scripts.
    113.                         }
    114.                     }
    115.                 }
    116.                 if (gotPosition == true  Input.touchCount > 0  fingerID > -1  fingerID < Input.touchCount) {
    117.                     if (Input.GetTouch(fingerID).phase == TouchPhase.Ended || Input.GetTouch(fingerID).phase == TouchPhase.Canceled) {ResetJoystick();}
    118.                 }
    119.                 if (gotPosition == false  fingerID == -1  tapTimer <= 0) {if (background.color != inactiveColor) {background.color = inactiveColor;}}
    120.                 //
    121.                 if (useAbsoluteScales) {
    122.                     if (joystickScale.Length < 2) {Debug.LogError(this.name+"(JVR): "+"Did you setup 'X,Y' absolute scales for the joystick? Set 'Size' = 2..."); return;}
    123.                     if (backgroundScale.Length < 2) {Debug.LogError(this.name+"(JVR): "+"Did you setup 'X,Y' absolute scales for the background? Set 'Size' = 2..."); return;}
    124.                     background.pixelInset = new Rect(origin.x-(background.pixelInset.width/2),origin.y-(background.pixelInset.height/2),backgroundScale[0],backgroundScale[1]);
    125.                     joystick.pixelInset = new Rect(position.x-(joystick.pixelInset.width/2),position.y-(joystick.pixelInset.height/2),joystickScale[0],joystickScale[1]);
    126.                 } else {
    127.                     background.pixelInset = new Rect(origin.x-(background.pixelInset.width/2),origin.y-(background.pixelInset.height/2),size/5,size/5);
    128.                     joystick.pixelInset = new Rect(position.x-(joystick.pixelInset.width/2),position.y-(joystick.pixelInset.height/2),size/11,size/11);
    129.                 }
    130.             } else if (background.pixelInset.width > 0) {background.pixelInset = new Rect(0,0,0,0); joystick.pixelInset = new Rect(0,0,0,0);}
    131.         }
    132.     }
    133.  
     
    Last edited: Jun 19, 2012
  26. nickavv

    nickavv

    Joined:
    Aug 2, 2006
    Posts:
    1,801
    Hi Bruno, I'm having the same issue as dasbin and AronD, the texture isn't showing up on screen, although I can see the GUITexture component being added in the inspector. I've changed the colors from default black as well

    Edit: Figured it out, I had changed the color, but left the alpha value at 0. Change the alpha value and the joystick appears!
     
    Last edited: Jun 23, 2012
  27. iphoneDeveloper

    iphoneDeveloper

    Joined:
    Aug 16, 2012
    Posts:
    13
    hey nice tutorial but i m not able to move the joystick at all its just stuck at one place in screen

    i guess VJR-Joystick Back the backObj is giving some error .. can u guide me if i need to name my gameobject or something ?
    right now i named just gameobject then it gave error .. then i named it VJR-Joystick Back n it didnt gave error but while running its just stuck
     
  28. BrUnO-XaVIeR

    BrUnO-XaVIeR

    Joined:
    Dec 6, 2010
    Posts:
    1,687
    Increase the alpha value of the colors for the joystick, else it won't be rendered.
    No need to name anything.
     
  29. iphoneDeveloper

    iphoneDeveloper

    Joined:
    Aug 16, 2012
    Posts:
    13
    i did changed the alpha values still the joystick is stuck n i cant see the backgroud color only

    thanx a lot for the quick reply :)
     
  30. BrUnO-XaVIeR

    BrUnO-XaVIeR

    Joined:
    Dec 6, 2010
    Posts:
    1,687
    Make sure the gameobject you attach the script has the transform at 0,0,0.
     
  31. iphoneDeveloper

    iphoneDeveloper

    Joined:
    Aug 16, 2012
    Posts:
    13
    thanx i was adding another guitexture to it which created a problem now solved and really amazing thing thanx a lot :)
     
  32. iphoneDeveloper

    iphoneDeveloper

    Joined:
    Aug 16, 2012
    Posts:
    13
    Can you help me converting this code in .js format ? i tried attaching this .cs to .js but then while running joystick its not working well
     
  33. BrUnO-XaVIeR

    BrUnO-XaVIeR

    Joined:
    Dec 6, 2010
    Posts:
    1,687
    Move the script to the Plugins folder and you can access its variables from any Js script.
    I dont use Js since 3 years ago, have no idea on how to convert anything to that anymore.
     
  34. iphoneDeveloper

    iphoneDeveloper

    Joined:
    Aug 16, 2012
    Posts:
    13
    thanx a lot :)
     
  35. iphoneDeveloper

    iphoneDeveloper

    Joined:
    Aug 16, 2012
    Posts:
    13
    Hi , Ur joystick code is amazing but its not working fine with the Penelope :- Player Relativer Joystick code .. can you please help i have tried a lot changing things but its not working fine ..
     
  36. BrUnO-XaVIeR

    BrUnO-XaVIeR

    Joined:
    Dec 6, 2010
    Posts:
    1,687
    To insert different code into existing project you would need to change how things work in that project, I know nothing about that project but I guess it has some kind of tutorial with it. You would need to study the project and learn how things are done in there and then make the changes you need (using the normals from this VJR to move the character); I'm sorry but I am very busy and I can't help you out on this one.
     
  37. iphoneDeveloper

    iphoneDeveloper

    Joined:
    Aug 16, 2012
    Posts:
    13
    ok no problem thanks a lot for your quick response ...
     
  38. Talirris

    Talirris

    Joined:
    Sep 26, 2012
    Posts:
    1
    Awesome! Thanks for sharing your code and giving easy to read instructions, it was very helpful.
     
  39. magarcan

    magarcan

    Joined:
    Sep 25, 2012
    Posts:
    34
    Any idea about how to use two of this Joysticks at the same time?
    I´ve tried adding offset parameter and set it up in both joysticks but when I press the second joystick it moves towards another position and when I move one joystick, the other moves at the same time...

    Cheers!
     
  40. mayank_b24

    mayank_b24

    Joined:
    Aug 21, 2012
    Posts:
    1
    First of all, Thanx for the great script.

    i am facing a problem in android device. :)
    Wheneve my game is running on the android device and the device goes to sleep, when awaked the joystick seems to be un responsive,rest of the gui buttons and everything else works fine ,but joystick sort of just get stuck. :confused: :(

    Please help!

    Thanx
     
  41. BrUnO-XaVIeR

    BrUnO-XaVIeR

    Joined:
    Dec 6, 2010
    Posts:
    1,687
    Try this: http://docs.unity3d.com/Documentation/ScriptReference/Screen-sleepTimeout.html
     
  42. BrUnO-XaVIeR

    BrUnO-XaVIeR

    Joined:
    Dec 6, 2010
    Posts:
    1,687
    You would need to create private fields instead of static values to use more than one stick at once.
     
  43. LiefLayer

    LiefLayer

    Joined:
    Jan 6, 2013
    Posts:
    65
    thank you a lot for share this and your help...
    but now I have another problem... the joystick work but the player don't move.
    now I use the ThirdPersonController, and the ThirdPersonCamera script... but I can't find the mobile version of this script...
    I try integrate the Joystick on the prefab of my player... but it doesn't work.
    Now I'm following the HarkAndSlashTutorial and I'm on video 62... but it's only for PC.

    if you or someone can help me...
     
  44. LiefLayer

    LiefLayer

    Joined:
    Jan 6, 2013
    Posts:
    65
    I finally figure out how to use joystick and move character. but there is a problem, I can't activate animations of my prefab that only move without walk, or run (with normal control animations works).

    Joystick joy = Joystick.GetInstance("joystick");
    if (joy != null){
    pc.transform.Translate(moveSpeed * Time.deltaTime * joy.AxisX, 0.0f, moveSpeed * Time.deltaTime * joy.AxisY);
    }
    }
    I think that there is a problem with this part and that this script don't use my normal 3rdCaracterController (that works only with PC).

    if you can I need some help for fix my script or convert the 3rdcaractercontroller for works with my joystick.

    I'd really appreciate your help
     
  45. BrUnO-XaVIeR

    BrUnO-XaVIeR

    Joined:
    Dec 6, 2010
    Posts:
    1,687
  46. LiefLayer

    LiefLayer

    Joined:
    Jan 6, 2013
    Posts:
    65
    Hurra
    Now it works.
    there are some problem with collider (when the character collides changes direction instead of stopping) but now I'm really tired if I will resolv this problem I will post the final code.
    if someone want to help resolv the collider problem I really appreciate.

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public enum CharacterState
    5. {
    6.     Idle = 0,
    7.     Walking = 1,
    8.     Trotting = 2,
    9.     Running = 3,
    10.     Jumping = 4,
    11. }
    12.  
    13. public class ThirdPersonController : MonoBehaviour
    14. {
    15.  
    16.     public AnimationClip idleAnimation;
    17.     public AnimationClip walkAnimation;
    18.     public AnimationClip runAnimation;
    19.     public AnimationClip jumpPoseAnimation;
    20.    
    21.     // our cube that will spin around
    22.     public GameObject cube;
    23.     VCAnalogJoystickBase joy = VCAnalogJoystickBase.GetInstance("stick");
    24.     // our container that we will translate
    25.     public GameObject cubeContainer;
    26.    
    27.     // the max speed which the cube moves at
    28.     public float moveSpeed2 = 5.0f;
    29.  
    30.     public float walkMaxAnimationSpeed = 0.75f;
    31.     public float trotMaxAnimationSpeed = 1.0f;
    32.     public float runMaxAnimationSpeed = 1.0f;
    33.     public float jumpAnimationSpeed = 1.15f;
    34.     public float landAnimationSpeed = 1.0f;
    35.  
    36.     private Animation _animation;
    37.  
    38.  
    39.  
    40.     public CharacterState _characterState;
    41.  
    42.     // The speed when walking
    43.     public float walkSpeed = 2.0f;
    44.     // after trotAfterSeconds of walking we trot with trotSpeed
    45.     public float trotSpeed = 4.0f;
    46.     // when pressing "Fire3" button (cmd) we start running
    47.     public float runSpeed = 6.0f;
    48.  
    49.     public float inAirControlAcceleration = 3.0f;
    50.  
    51.     // How high do we jump when pressing jump and letting go immediately
    52.     public float jumpHeight = 0.5f;
    53.  
    54.     // The gravity for the character
    55.     public float gravity = 20.0f;
    56.     // The gravity in controlled descent mode
    57.     public float speedSmoothing = 10.0f;
    58.     public float rotateSpeed = 500.0f;
    59.     public float trotAfterSeconds = 3.0f;
    60.  
    61.     public bool canJump = false;
    62.  
    63.     private float jumpRepeatTime = 0.05f;
    64.     private float jumpTimeout = 0.15f;
    65.     private float groundedTimeout = 0.25f;
    66.  
    67.     // The camera doesnt start following the target immediately but waits for a split second to avoid too much waving around.
    68.     private float lockCameraTimer = 0.0f;
    69.  
    70.     // The current move direction in x-z
    71.     private Vector3 moveDirection = Vector3.zero;
    72.     // The current vertical speed
    73.     private float verticalSpeed = 0.0f;
    74.     // The current x-z move speed
    75.     private float moveSpeed = 0.0f;
    76.  
    77.     // The last collision flags returned from controller.Move
    78.     private CollisionFlags collisionFlags;
    79.  
    80.     // Are we jumping? (Initiated with jump button and not grounded yet)
    81.     private bool jumping = false;
    82.     private bool jumpingReachedApex = false;
    83.  
    84.     // Are we moving backwards (This locks the camera to not do a 180 degree spin)
    85.     private bool movingBack = false;
    86.     // Is the user pressing any keys?
    87.     private bool isMoving = false;
    88.     // When did the user start walking (Used for going into trot after a while)
    89.     private float walkTimeStart = 0.0f;
    90.     // Last time the jump button was clicked down
    91.     private float lastJumpButtonTime = -10.0f;
    92.     // Last time we performed a jump
    93.     private float lastJumpTime = -1.0f;
    94.     // the height we jumped from (Used to determine for how long to apply extra jump power after jumping.)
    95.     //private float lastJumpStartHeight = 0.0f;
    96.     private Vector3 inAirVelocity = Vector3.zero;
    97.  
    98.     private float lastGroundedTime = 0.0f;
    99.     public bool isControllable = true;
    100.  
    101.     void Awake()
    102.     {
    103.         moveDirection = transform.TransformDirection(Vector3.forward);
    104.  
    105.         _animation = GetComponent<Animation>();
    106.         if (!_animation)
    107.             Debug.Log("The character you would like to control doesn't have animations. Moving her might look weird.");
    108.  
    109.         /*
    110.     public AnimationClip idleAnimation;
    111.     public AnimationClip walkAnimation;
    112.     public AnimationClip runAnimation;
    113.     public AnimationClip jumpPoseAnimation;
    114.         */
    115.         if (!idleAnimation)
    116.         {
    117.             _animation = null;
    118.             Debug.Log("No idle animation found. Turning off animations.");
    119.         }
    120.         if (!walkAnimation)
    121.         {
    122.             _animation = null;
    123.             Debug.Log("No walk animation found. Turning off animations.");
    124.         }
    125.         if (!runAnimation)
    126.         {
    127.             _animation = null;
    128.             Debug.Log("No run animation found. Turning off animations.");
    129.         }
    130.         if (!jumpPoseAnimation  canJump)
    131.         {
    132.             _animation = null;
    133.             Debug.Log("No jump animation found and the character has canJump enabled. Turning off animations.");
    134.         }
    135.  
    136.     }
    137.  
    138.     private Vector3 lastPos;
    139.  
    140.     void UpdateSmoothedMovementDirection()
    141.     {
    142.         Transform cameraTransform = Camera.main.transform;
    143.         bool grounded = IsGrounded();
    144.  
    145.         // Forward vector relative to the camera along the x-z plane   
    146.         Vector3 forward = cameraTransform.TransformDirection(Vector3.forward);
    147.         forward.y = 0;
    148.         forward = forward.normalized;
    149.  
    150.         // Right vector relative to the camera
    151.         // Always orthogonal to the forward vector
    152.         Vector3 right = new Vector3(forward.z, 0, -forward.x);
    153.  
    154.         float v = Input.GetAxisRaw("Vertical");
    155.         float h = Input.GetAxisRaw("Horizontal");
    156.        
    157.         // Are we moving backwards or looking backwards
    158.         if (v < -0.2f)
    159.             movingBack = true;
    160.         else
    161.             movingBack = false;
    162.  
    163.         bool wasMoving = isMoving;
    164.         isMoving = Mathf.Abs(h) > 0.1f || Mathf.Abs(v) > 0.1f;
    165.  
    166.         // Target direction relative to the camera
    167.         Vector3 targetDirection = h * right + v * forward;
    168.  
    169.         // Grounded controls
    170.         if (grounded)
    171.         {
    172.             // Lock camera for short period when transitioning moving  standing still
    173.             lockCameraTimer += Time.deltaTime;
    174.             if (isMoving != wasMoving)
    175.                 lockCameraTimer = 0.0f;
    176.  
    177.             // We store speed and direction seperately,
    178.             // so that when the character stands still we still have a valid forward direction
    179.             // moveDirection is always normalized, and we only update it if there is user input.
    180.             if (targetDirection != Vector3.zero)
    181.             {
    182.                 // If we are really slow, just snap to the target direction
    183.                 if (moveSpeed < walkSpeed * 0.9f  grounded)
    184.                 {
    185.                     moveDirection = targetDirection.normalized;
    186.                 }
    187.                 // Otherwise smoothly turn towards it
    188.                 else
    189.                 {
    190.                     moveDirection = Vector3.RotateTowards(moveDirection, targetDirection, rotateSpeed * Mathf.Deg2Rad * Time.deltaTime, 1000);
    191.  
    192.                     moveDirection = moveDirection.normalized;
    193.                 }
    194.             }
    195.  
    196.             // Smooth the speed based on the current target direction
    197.             float curSmooth = speedSmoothing * Time.deltaTime;
    198.  
    199.             // Choose target speed
    200.             //* We want to support analog input but make sure you cant walk faster diagonally than just forward or sideways
    201.             float targetSpeed = Mathf.Min(targetDirection.magnitude, 1.0f);
    202.  
    203.             _characterState = CharacterState.Idle;
    204.  
    205.             // Pick speed modifier
    206.             if (Input.GetKey(KeyCode.LeftShift) | Input.GetKey(KeyCode.RightShift))
    207.             {
    208.                 targetSpeed *= runSpeed;
    209.                 _characterState = CharacterState.Running;
    210.             }
    211.             else if (Time.time - trotAfterSeconds > walkTimeStart)
    212.             {
    213.                 targetSpeed *= trotSpeed;
    214.                 _characterState = CharacterState.Trotting;
    215.             }
    216.             else
    217.             {
    218.                 targetSpeed *= walkSpeed;
    219.                 _characterState = CharacterState.Walking;
    220.             }
    221.  
    222.             moveSpeed = Mathf.Lerp(moveSpeed, targetSpeed, curSmooth);
    223.  
    224.             // Reset walk time start when we slow down
    225.             if (moveSpeed < walkSpeed * 0.3f)
    226.                 walkTimeStart = Time.time;
    227.         }
    228.         // In air controls
    229.         else
    230.         {
    231.             // Lock camera while in air
    232.             if (jumping)
    233.                 lockCameraTimer = 0.0f;
    234.  
    235.             if (isMoving)
    236.                 inAirVelocity += targetDirection.normalized * Time.deltaTime * inAirControlAcceleration;
    237.         }
    238.  
    239.  
    240.  
    241.     }
    242.     void ApplyJumping()
    243.     {
    244.         // Prevent jumping too fast after each other
    245.         if (lastJumpTime + jumpRepeatTime > Time.time)
    246.             return;
    247.  
    248.         if (IsGrounded())
    249.         {
    250.             // Jump
    251.             // - Only when pressing the button down
    252.             // - With a timeout so you can press the button slightly before landing    
    253.             if (canJump  Time.time < lastJumpButtonTime + jumpTimeout)
    254.             {
    255.                 verticalSpeed = CalculateJumpVerticalSpeed(jumpHeight);
    256.                 SendMessage("DidJump", SendMessageOptions.DontRequireReceiver);
    257.             }
    258.         }
    259.     }
    260.     void ApplyGravity()
    261.     {
    262.         if (isControllable) // don't move player at all if not controllable.
    263.         {
    264.             // Apply gravity
    265.             //bool jumpButton = Input.GetButton("Jump");
    266.            
    267.             // When we reach the apex of the jump we send out a message
    268.             if (jumping  !jumpingReachedApex  verticalSpeed <= 0.0f)
    269.             {
    270.                 jumpingReachedApex = true;
    271.                 SendMessage("DidJumpReachApex", SendMessageOptions.DontRequireReceiver);
    272.             }
    273.  
    274.             if (IsGrounded())
    275.                 verticalSpeed = 0.0f;
    276.             else
    277.                 verticalSpeed -= gravity * Time.deltaTime;
    278.         }
    279.     }
    280.  
    281.     float CalculateJumpVerticalSpeed(float targetJumpHeight)
    282.     {
    283.         // From the jump height and gravity we deduce the upwards speed
    284.         // for the character to reach at the apex.
    285.         return Mathf.Sqrt(2 * targetJumpHeight * gravity);
    286.     }
    287.  
    288.     void DidJump()
    289.     {
    290.         jumping = true;
    291.         jumpingReachedApex = false;
    292.         lastJumpTime = Time.time;
    293.         //lastJumpStartHeight = transform.position.y;
    294.         lastJumpButtonTime = -10;
    295.  
    296.         _characterState = CharacterState.Jumping;
    297.     }
    298.  
    299.     Vector3 velocity = Vector3.zero;
    300.  
    301.     void Update()
    302.     {        
    303.         if (isControllable)
    304.         {
    305.             if (Input.GetButtonDown("Jump"))
    306.             {
    307.                 lastJumpButtonTime = Time.time;
    308.             }
    309.  
    310.             UpdateSmoothedMovementDirection();
    311.  
    312.             // Apply gravity
    313.             // - extra power jump modifies gravity
    314.             // - controlledDescent mode modifies gravity
    315.             ApplyGravity();
    316.  
    317.             // Apply jumping logic
    318.             ApplyJumping();
    319.  
    320.  
    321.             // Calculate actual motion
    322.             Vector3 movement = moveDirection * moveSpeed + new Vector3(0, verticalSpeed, 0) + inAirVelocity;
    323.             movement *= Time.deltaTime;
    324.  
    325.             // Move the controller
    326.             CharacterController controller = GetComponent<CharacterController>();
    327.                 cubeContainer = GameObject.Find("pc");
    328.         cube = GameObject.Find("249HumanAnimated");
    329.         if (joy != null){
    330.                 if(controller.isGrounded){
    331.             moveDirection = new Vector3(joy.AxisX, 0, joy.AxisY);
    332.             moveDirection = cubeContainer.transform.TransformDirection(moveDirection);
    333.             moveDirection *= walkSpeed;
    334.                 }
    335.             }
    336.            
    337.               // Move the controller
    338.     controller.Move(moveDirection * Time.deltaTime);
    339.  
    340.             collisionFlags = controller.Move(movement);
    341.         }
    342.         velocity = (transform.position - lastPos)*25;
    343.  
    344.         // ANIMATION sector
    345.         if (_animation)
    346.         {
    347.             if (_characterState == CharacterState.Jumping)
    348.             {
    349.                 if (!jumpingReachedApex)
    350.                 {
    351.                     _animation[jumpPoseAnimation.name].speed = jumpAnimationSpeed;
    352.                     _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever;
    353.                     _animation.CrossFade(jumpPoseAnimation.name);
    354.                 }
    355.                 else
    356.                 {
    357.                     _animation[jumpPoseAnimation.name].speed = -landAnimationSpeed;
    358.                     _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever;
    359.                     _animation.CrossFade(jumpPoseAnimation.name);
    360.                 }
    361.             }
    362.             else
    363.             {
    364.                 if (velocity.sqrMagnitude < 0.001f)
    365.                 {
    366.                     _animation.CrossFade(idleAnimation.name);
    367.                 }
    368.                 else
    369.                 {
    370.                     if (_characterState == CharacterState.Running)
    371.                     {
    372.                         _animation[runAnimation.name].speed = Mathf.Clamp(velocity.magnitude, 0.0f, runMaxAnimationSpeed);
    373.                         _animation.CrossFade(runAnimation.name);
    374.                     }
    375.                     else if (_characterState == CharacterState.Trotting)
    376.                     {
    377.                         _animation[walkAnimation.name].speed = Mathf.Clamp(velocity.magnitude, 0.0f, trotMaxAnimationSpeed);
    378.                         _animation.CrossFade(walkAnimation.name);
    379.                     }
    380.                     else if (_characterState == CharacterState.Walking)
    381.                     {
    382.                         _animation[walkAnimation.name].speed = Mathf.Clamp(velocity.magnitude, 0.0f, walkMaxAnimationSpeed);
    383.                         _animation.CrossFade(walkAnimation.name);
    384.                     }
    385.  
    386.                 }
    387.             }
    388.         }
    389.         // ANIMATION sector
    390.  
    391.         // Set rotation to the move direction
    392.         if (IsGrounded())
    393.         {
    394.             moveDirection = transform.TransformDirection(Vector3.forward);
    395.             transform.rotation = Quaternion.LookRotation(moveDirection);
    396.  
    397.         }
    398.         else
    399.         {
    400.             Vector3 xzMove = velocity;
    401.             xzMove.y = 0;
    402.             if (xzMove.sqrMagnitude > 0.001f)
    403.             {
    404.                 transform.rotation = Quaternion.LookRotation(xzMove);
    405.             }
    406.         }
    407.  
    408.         // We are in jump mode but just became grounded
    409.         if (IsGrounded())
    410.         {
    411.             lastGroundedTime = Time.time;
    412.             inAirVelocity = Vector3.zero;
    413.             if (jumping)
    414.             {
    415.                 jumping = false;
    416.                 SendMessage("DidLand", SendMessageOptions.DontRequireReceiver);
    417.             }
    418.         }
    419.  
    420.         lastPos = transform.position;
    421.     }
    422.  
    423.     void OnControllerColliderHit(ControllerColliderHit hit)
    424.     {
    425.         //  Debug.DrawRay(hit.point, hit.normal);
    426.         if (hit.moveDirection.y > 0.01f)
    427.             return;
    428.     }
    429.  
    430.     public float GetSpeed()
    431.     {
    432.         return moveSpeed;
    433.     }
    434.  
    435.     public bool IsJumping()
    436.     {
    437.         return jumping;
    438.     }
    439.  
    440.     public bool IsGrounded()
    441.     {
    442.         return (collisionFlags  CollisionFlags.CollidedBelow) != 0;
    443.     }
    444.  
    445.     public Vector3 GetDirection()
    446.     {
    447.         return moveDirection;
    448.     }
    449.  
    450.     public bool IsMovingBackwards()
    451.     {
    452.         return movingBack;
    453.     }
    454.  
    455.     public float GetLockCameraTimer()
    456.     {
    457.         return lockCameraTimer;
    458.     }
    459.  
    460.     public bool IsMoving()
    461.     {
    462.         return Mathf.Abs(Input.GetAxisRaw("Vertical")) + Mathf.Abs(Input.GetAxisRaw("Horizontal")) > 0.5f;
    463.     }
    464.  
    465.     public bool HasJumpReachedApex()
    466.     {
    467.         return jumpingReachedApex;
    468.     }
    469.  
    470.     public bool IsGroundedWithTimeout()
    471.     {
    472.         return lastGroundedTime + groundedTimeout > Time.time;
    473.     }
    474.  
    475.     public void Reset()
    476.     {
    477.         gameObject.tag = "Player";
    478.     }
    479.  
    480.  
    481. }
    thank you BrUnO XaVIeR for your patience
     
    Last edited: Feb 8, 2013
  47. BrUnO-XaVIeR

    BrUnO-XaVIeR

    Joined:
    Dec 6, 2010
    Posts:
    1,687
    Sorry, I can't see anything wrong with that script.
    I think this is code from Unity's 2D tutorial, the problem must be somewhere else in that project.
     
  48. josecivera

    josecivera

    Joined:
    Mar 19, 2013
    Posts:
    4
    Hello, I don't have much coding experience, and after adding the gameObject and the script code, my program shows the virtual joystick ok, but I don't now I don't now how to retrieve the x and y coordinates (VJRnormals) from my code.

    Could someone provide me some sample about how to access it?

    I have tried this, that compiles ok, but does not seem to retrieve the coordinate value (my GameObjet is named VJR):

    x = GameObject.Find("VJR").GetComponent(VirtualJoystickRegion).VJRnormals.x;
     
  49. BrUnO-XaVIeR

    BrUnO-XaVIeR

    Joined:
    Dec 6, 2010
    Posts:
    1,687
    Post a copy of your script please. A single line is not enough for us to check it out.
     
  50. josecivera

    josecivera

    Joined:
    Mar 19, 2013
    Posts:
    4
    I am trying to modify a game designed for being played with keys in the PC in order to play it in my Android mobile, and for the moment I was trying to check that I can read the joystick position right, to replace the key input section with screen joystick input afterwards.

    So maybe my question is too naive, but it is how to read the joystick position.

    var message = "joys x:";
    message+= GameObject.Find("VJR").GetComponent(VirtualJoystickRegion).VJRnormals.x;
    message+=" y:";
    message+= GameObject.Find("VJR").GetComponent(VirtualJoystickRegion).VJRnormals.y;
    GUI.Label ( Rect( 20, 20, 310, 35),message, "label");

    Now it shows "joys x:0,y:0" although I am moving the joystick.

    So, in the Update function of the thirdpersoncontroller script or for example in the OnGui function, which variable do I have to instantiate to acces the joystick?

    Thank you.
     
    Last edited: Mar 19, 2013