Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Touchscreen Steering Wheel Rotation Example (Mouse Supported)

Discussion in 'Community Learning & Teaching' started by yasirkula, Aug 21, 2013.

  1. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,865
    UPDATE (16/04/2018): Updated the UI script to work correctly even after screen resolution/orientation changes runtime

    Hi there,

    I'd like to share with you a simple code to simulate a 2D Steering Wheel for use in (mostly) mobile racing games. There are two versions of the code and you only need to use one of them:

    • Using new UI system
    I used C# for this version. You need to create a UI Image containing the wheel sprite anywhere in your canvas. Do not add an Event Trigger component to the Image if possible (otherwise, I don't know what will happen). Make sure that the pivot of the Image is set correctly (i.e. changing the Rotation-Z value of the Image does not rotate it awkwardly).

    After everything is set, add the script below as a component to any GameObject you want and then give the steering wheel Image as value to the UI_Element variable via Inspector. And finally, test it!

    NOTE: Use GetClampedValue() to get a value in range [-1,1] (both inclusive), and GetAngle() to get the angle of the steering wheel directly (not recommended).

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using UnityEngine.EventSystems;
    4. using UnityEngine.Events;
    5. using System.Collections;
    6.  
    7. public class SteeringWheel : MonoBehaviour
    8. {
    9.     public Graphic UI_Element;
    10.  
    11.     RectTransform rectT;
    12.     Vector2 centerPoint;
    13.  
    14.     public float maximumSteeringAngle = 200f;
    15.     public float wheelReleasedSpeed = 200f;
    16.  
    17.     float wheelAngle = 0f;
    18.     float wheelPrevAngle = 0f;
    19.  
    20.     bool wheelBeingHeld = false;
    21.  
    22.     public float GetClampedValue()
    23.     {
    24.         // returns a value in range [-1,1] similar to GetAxis("Horizontal")
    25.         return wheelAngle / maximumSteeringAngle;
    26.     }
    27.  
    28.     public float GetAngle()
    29.     {
    30.         // returns the wheel angle itself without clamp operation
    31.         return wheelAngle;
    32.     }
    33.  
    34.     void Start()
    35.     {
    36.         rectT = UI_Element.rectTransform;
    37.         InitEventsSystem();
    38.     }
    39.  
    40.     void Update()
    41.     {
    42.         // If the wheel is released, reset the rotation
    43.         // to initial (zero) rotation by wheelReleasedSpeed degrees per second
    44.         if( !wheelBeingHeld && !Mathf.Approximately( 0f, wheelAngle ) )
    45.         {
    46.             float deltaAngle = wheelReleasedSpeed * Time.deltaTime;
    47.             if( Mathf.Abs( deltaAngle ) > Mathf.Abs( wheelAngle ) )
    48.                 wheelAngle = 0f;
    49.             else if( wheelAngle > 0f )
    50.                 wheelAngle -= deltaAngle;
    51.             else
    52.                 wheelAngle += deltaAngle;
    53.         }
    54.  
    55.         // Rotate the wheel image
    56.         rectT.localEulerAngles = Vector3.back * wheelAngle;
    57.     }
    58.  
    59.     void InitEventsSystem()
    60.     {
    61.         // Warning: Be ready to see some extremely boring code here :-/
    62.         // You are warned!
    63.         EventTrigger events = UI_Element.gameObject.GetComponent<EventTrigger>();
    64.  
    65.         if( events == null )
    66.             events = UI_Element.gameObject.AddComponent<EventTrigger>();
    67.  
    68.         if( events.triggers == null )
    69.             events.triggers = new System.Collections.Generic.List<EventTrigger.Entry>();
    70.  
    71.         EventTrigger.Entry entry = new EventTrigger.Entry();
    72.         EventTrigger.TriggerEvent callback = new EventTrigger.TriggerEvent();
    73.         UnityAction<BaseEventData> functionCall = new UnityAction<BaseEventData>( PressEvent );
    74.         callback.AddListener( functionCall );
    75.         entry.eventID = EventTriggerType.PointerDown;
    76.         entry.callback = callback;
    77.  
    78.         events.triggers.Add( entry );
    79.  
    80.         entry = new EventTrigger.Entry();
    81.         callback = new EventTrigger.TriggerEvent();
    82.         functionCall = new UnityAction<BaseEventData>( DragEvent );
    83.         callback.AddListener( functionCall );
    84.         entry.eventID = EventTriggerType.Drag;
    85.         entry.callback = callback;
    86.  
    87.         events.triggers.Add( entry );
    88.  
    89.         entry = new EventTrigger.Entry();
    90.         callback = new EventTrigger.TriggerEvent();
    91.         functionCall = new UnityAction<BaseEventData>( ReleaseEvent );//
    92.         callback.AddListener( functionCall );
    93.         entry.eventID = EventTriggerType.PointerUp;
    94.         entry.callback = callback;
    95.  
    96.         events.triggers.Add( entry );
    97.     }
    98.  
    99.     public void PressEvent( BaseEventData eventData )
    100.     {
    101.         // Executed when mouse/finger starts touching the steering wheel
    102.         Vector2 pointerPos = ( (PointerEventData) eventData ).position;
    103.  
    104.         wheelBeingHeld = true;
    105.         centerPoint = RectTransformUtility.WorldToScreenPoint( ( (PointerEventData) eventData ).pressEventCamera, rectT.position );
    106.         wheelPrevAngle = Vector2.Angle( Vector2.up, pointerPos - centerPoint );
    107.     }
    108.  
    109.     public void DragEvent( BaseEventData eventData )
    110.     {
    111.         // Executed when mouse/finger is dragged over the steering wheel
    112.         Vector2 pointerPos = ( (PointerEventData) eventData ).position;
    113.  
    114.         float wheelNewAngle = Vector2.Angle( Vector2.up, pointerPos - centerPoint );
    115.         // Do nothing if the pointer is too close to the center of the wheel
    116.         if( Vector2.Distance( pointerPos, centerPoint ) > 20f )
    117.         {
    118.             if( pointerPos.x > centerPoint.x )
    119.                 wheelAngle += wheelNewAngle - wheelPrevAngle;
    120.             else
    121.                 wheelAngle -= wheelNewAngle - wheelPrevAngle;
    122.         }
    123.         // Make sure wheel angle never exceeds maximumSteeringAngle
    124.         wheelAngle = Mathf.Clamp( wheelAngle, -maximumSteeringAngle, maximumSteeringAngle );
    125.         wheelPrevAngle = wheelNewAngle;
    126.     }
    127.  
    128.     public void ReleaseEvent( BaseEventData eventData )
    129.     {
    130.         // Executed when mouse/finger stops touching the steering wheel
    131.         // Performs one last DragEvent, just in case
    132.         DragEvent( eventData );
    133.  
    134.         wheelBeingHeld = false;
    135.     }
    136. }
    • Using legacy GUI (using OnGUI) system
    Script supports both PC (& Linux & MAC) and mobile platforms. You can fetch the value of the steering wheel using the GetAngle() function (see comments). If you would like to change the position of the steering wheel on screen, all you need to do is to change the value of wheelPosition in the Start() function.

    Here is the Javascript code:

    Code (csharp):
    1. #pragma strict
    2.  
    3. public var maximumAngle : float = 500f; // Maximum angle the steering wheel can rotate
    4. public var wheelSize : float = 256f; // Wheel's width (and height) as pixel
    5. public var deltaPivot : Vector2 = Vector2.zero; // If wheel not rotates around its center, this variable allows tweaking the pivot point
    6. public var wheelFreeSpeed : float = 200f; // Degrees per second the wheel rotates when released
    7. public var wheelTexture : Texture2D; // Wheel texture
    8.  
    9. private var wheelAngle : float; // Wheel's angle in degrees
    10.  
    11. private var wheelBeingHeld : boolean; // Whether or not the steering wheel is being held
    12. private var wheelPosition : Rect; // Wheel's position on screen
    13. private var wheelCenter : Vector2; // Wheel's center on screen coordinates (not Rect coordinates)
    14. private var wheelTempAngle : float; // A necessary variable
    15.  
    16. function Start()
    17. {
    18.    // Initialize variables and calculate wheel's position on screen
    19.    wheelBeingHeld = false;
    20.    wheelPosition = new Rect( Screen.width - wheelSize - 75, Screen.height - wheelSize - 75, wheelSize, wheelSize );
    21.    wheelCenter = new Vector2( wheelPosition.x + wheelPosition.width * 0.5f, Screen.height - wheelPosition.y - wheelPosition.height * 0.5f );
    22.    wheelAngle = 0f;
    23. }
    24.  
    25. // Returns the angle of the steering wheel. Can be used to rotate a car etc.
    26. // Resulting value is always between -1.0 (inclusive) and 1.0 (inclusive)
    27. // Resulting value will be positive while the wheel is rotated to the right
    28. // Resulting value will be negative while the wheel is rotated to the left
    29. public function GetAngle()
    30. {
    31.    return wheelAngle / maximumAngle;
    32. }
    33.  
    34. // Draw the steering wheel on screen
    35. function OnGUI()
    36. {
    37.    // Uncomment the line below to see the bounds of the wheel
    38.    // GUI.Box( wheelPosition, "" );
    39.  
    40.    var theMatrix : Matrix4x4 = GUI.matrix;
    41.    GUIUtility.RotateAroundPivot( wheelAngle, wheelPosition.center + deltaPivot );
    42.    GUI.DrawTexture( wheelPosition, wheelTexture );
    43.    GUI.matrix = theMatrix;
    44. }
    45.  
    46. #if UNITY_EDITOR || UNITY_STANDALONE || UNITY_WEBPLAYER
    47. /*
    48. ** This code is executed on Unity Editor, Windows, MAC, Linux and Web Player only
    49. */
    50. function Update()
    51. {
    52.    // If the wheel is currently being held
    53.    if( wheelBeingHeld )
    54.    {
    55.      var mousePosition : Vector2;
    56.  
    57.      // Find the mouse position on screen
    58.      mousePosition = Input.mousePosition;
    59.  
    60.      var wheelNewAngle : float = Vector2.Angle( Vector2.up, mousePosition - wheelCenter );
    61.  
    62.      // If mouse is very close to the steering wheel's center, do nothing
    63.      if( Vector2.Distance( mousePosition, wheelCenter ) > 20f )
    64.      {
    65.        if( mousePosition.x > wheelCenter.x )
    66.          wheelAngle += wheelNewAngle - wheelTempAngle;
    67.        else
    68.          wheelAngle -= wheelNewAngle - wheelTempAngle;
    69.      }
    70.  
    71.      // Make sure that the wheelAngle does not exceed the maximumAngle
    72.      if( wheelAngle > maximumAngle )
    73.        wheelAngle = maximumAngle;
    74.      else if( wheelAngle < -maximumAngle )
    75.        wheelAngle = -maximumAngle;
    76.  
    77.      wheelTempAngle = wheelNewAngle;
    78.  
    79.      // If user releases the mouse, release the wheel
    80.      if( Input.GetMouseButtonUp( 0 ) )
    81.        wheelBeingHeld = false;
    82.    }
    83.    else // If wheel is not being held
    84.    {
    85.      // If user clicks on the wheel, update the status
    86.      if( Input.GetMouseButtonDown( 0 ) && wheelPosition.Contains( new Vector2( Input.mousePosition.x, Screen.height - Input.mousePosition.y ) ) )
    87.      {
    88.        wheelBeingHeld = true;
    89.        wheelTempAngle = Vector2.Angle( Vector2.up, Input.mousePosition - wheelCenter );
    90.      }
    91.  
    92.      // If the wheel is rotated and not being held, rotate it to its default angle (zero)
    93.      if( !Mathf.Approximately( 0f, wheelAngle ) )
    94.      {
    95.        var deltaAngle : float = wheelFreeSpeed * Time.deltaTime;
    96.  
    97.        if( Mathf.Abs( deltaAngle ) > Mathf.Abs( wheelAngle ) )
    98.        {
    99.          wheelAngle = 0f;
    100.          return;
    101.        }
    102.  
    103.        if( wheelAngle > 0f )
    104.          wheelAngle -= deltaAngle;
    105.        else
    106.          wheelAngle += deltaAngle;
    107.      }
    108.    }
    109. }
    110. #else
    111. /*
    112. ** This code is executed on mobile platforms only
    113. */
    114. private var touchId : int = -1; // The finger holding the wheel
    115.  
    116. function Update()
    117. {
    118.    // If the wheel is currently being held
    119.    if( wheelBeingHeld )
    120.    {
    121.      var touchPosition : Vector2;
    122.  
    123.      // Find the finger position on screen
    124.      for( var t : Touch in Input.touches )
    125.      {
    126.        if( t.fingerId == touchId )
    127.        {
    128.          touchPosition = t.position;
    129.  
    130.          // If finger exists no more, release the wheel
    131.          if( t.phase == TouchPhase.Ended || t.phase == TouchPhase.Canceled )
    132.          {
    133.            wheelBeingHeld = false;
    134.          }
    135.        }
    136.      }
    137.  
    138.      var wheelNewAngle : float = Vector2.Angle( Vector2.up, touchPosition - wheelCenter );
    139.  
    140.      // If touch is very close to the steering wheel's center, do nothing
    141.      if( Vector2.Distance( touchPosition, wheelCenter ) > 20f )
    142.      {
    143.        if( touchPosition.x > wheelCenter.x )
    144.          wheelAngle += wheelNewAngle - wheelTempAngle;
    145.        else
    146.          wheelAngle -= wheelNewAngle - wheelTempAngle;
    147.      }
    148.  
    149.      // Make sure that the wheelAngle does not exceed the maximumAngle
    150.      if( wheelAngle > maximumAngle )
    151.        wheelAngle = maximumAngle;
    152.      else if( wheelAngle < -maximumAngle )
    153.        wheelAngle = -maximumAngle;
    154.  
    155.      wheelTempAngle = wheelNewAngle;
    156.    }
    157.    else // If wheel is not being held
    158.    {
    159.      // If a finger touches the wheel, update the status
    160.      for( var t : Touch in Input.touches )
    161.      {
    162.        if( t.phase == TouchPhase.Began )
    163.        {
    164.          if( wheelPosition.Contains( new Vector2( t.position.x, Screen.height - t.position.y ) ) )
    165.          {
    166.            wheelBeingHeld = true;
    167.            wheelTempAngle = Vector2.Angle( Vector2.up, t.position - wheelCenter );
    168.            touchId = t.fingerId;
    169.          }
    170.        }
    171.      }
    172.  
    173.      // If the wheel is rotated and not being held, rotate it to its default angle (zero)
    174.      if( !Mathf.Approximately( 0f, wheelAngle ) )
    175.      {
    176.        var deltaAngle : float = wheelFreeSpeed * Time.deltaTime;
    177.  
    178.        if( Mathf.Abs( deltaAngle ) > Mathf.Abs( wheelAngle ) )
    179.        {
    180.          wheelAngle = 0f;
    181.          return;
    182.        }
    183.  
    184.        if( wheelAngle > 0f )
    185.          wheelAngle -= deltaAngle;
    186.        else
    187.          wheelAngle += deltaAngle;
    188.      }
    189.    }
    190. }
    191. #endif
    If you'd like to see it (the legacy version) in action, here is an example scene in which you control a car using the steering wheel.

    Hope you like it. If you have a question, please ask...

    Have a nice day!
     
    Last edited: Apr 16, 2018
  2. Zainj

    Zainj

    Joined:
    Nov 5, 2013
    Posts:
    1
    Finally found it... Have been looking for this for almost a day... going to use it and tweak it according to my needs... will let you know how it works out for me...
     
  3. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,865
    I'm glad that you liked it. Thanks for giving it a try.
     
  4. ravi83

    ravi83

    Joined:
    Jul 19, 2014
    Posts:
    5
    This Script is very helpful, i am working on car parking game when i build this for android my steering wheel positon and scaling is disturb. please help.
     
  5. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,865
    Are you attaching the script to a GUI Texture? If so, don't do this because script uses OnGUI function to manually draw wheel texture instead of using the GUI Texture. However GUI Texture idea seems really interesting. Maybe I can give GUI Texture support, too.

    If your issue is not about attaching script to a GUITexture, please check whether your wheel texture's dimensions are equal (width = height). When you are sure that dimensions are equal, you can scale the wheel using the wheelSize variable and change its position manually by changing the "wheelPosition" in the Start function.

    Please let me know if you have anymore issues. Thank you for your interest in this script :)
     
  6. ravi83

    ravi83

    Joined:
    Jul 19, 2014
    Posts:
    5
    Yes its works thanks... I have one more issue this game have multi touch event so the problem is when I use this script for rotating my car the slider don't work. I am attaching image and also wheel rotation script .
     

    Attached Files:

  7. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,865
    You are using "GUI.VerticalSlider" to create the slider. However, unfortunately, none of the GUI elements (like buttons, toggles, sliders etc.) support multi-touch.

    As far as I observed, when there are two fingers on the screen, the middle point of these two touches' position is considered as the touch position by the Unity GUI system. Multi-touch can only be achieved using Input.touches (and sometimes fingerId). Steering wheel supports multi-touch but I think you can't change the default behaviour of Unity sliders, which don't use Input.touches and are expecting only one touch on the screen at a time.

    How to solve this problem? I can't think of anything other than creating your own slider class from scratch.
     
  8. herman111

    herman111

    Joined:
    May 11, 2014
    Posts:
    119
    if I attach the script to a cube...how do I rotate the cube with this script?
     
  9. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,865
    When you give the wheelTexture property its value (a steering wheel texture), it will be shown on the screen (in Game View). Then you can access the script and use its GetAngle() function to rotate the cube. GetAngle() returns the angle of the wheel (negative if you turn it left, positive if you turn it right). You may use Physics.AddForce (or possibly AddForceAtPosition) to rotate the cube.
     
  10. ravi83

    ravi83

    Joined:
    Jul 19, 2014
    Posts:
    5
    Can i attach another GuiTexture as a button for speed of car in your wheel rotation script.

    if( wheelBeingHeld )
    {
    foreach(Touch t in Input.touches )
    {
    if( t.fingerId == touchId )
    {
    touchPosition = t.position;
    if( t.phase == TouchPhase.Ended || t.phase == TouchPhase.Canceled )
    {
    wheelBeingHeld = false;
    }
    }
    }
    float wheelNewAngle = Vector2.Angle( Vector2.up, touchPosition - wheelCenter);

    if( Vector2.Distance( touchPosition, wheelCenter ) > 20f )
    {
    if( touchPosition.x > wheelCenter.x )
    wheelAngle += wheelNewAngle - wheelTempAngle;
    else
    wheelAngle -= wheelNewAngle - wheelTempAngle;
    }

    if( wheelAngle > maximumAngle )
    wheelAngle = maximumAngle;
    else if( wheelAngle < -maximumAngle )
    wheelAngle = -maximumAngle;

    wheelTempAngle = wheelNewAngle;
    }
    else
    {
    foreach( Touch touch in Input.touches ){
    if( touch.phase == TouchPhase.Began)
    {
    if( wheelPosition.Contains( new Vector2( touch.position.x, Screen.height - touch.position.y ) ) )
    {
    wheelBeingHeld = true;
    wheelTempAngle = Vector2.Angle( Vector2.up, touch.position - wheelCenter );
    touchId =touch.fingerId;
    }
    }

    if (touch.phase == TouchPhase.Began && speed.HitTest (touch.position)) {
    speedupcar+=Time.deltaTime;
    }
    else if (touch.phase == TouchPhase.Ended){
    speedupcar-=Time.deltaTime;
    }

    }
    if( !Mathf.Approximately( 0f, wheelAngle ) )
    {
    float deltaAngle = wheelFreeSpeed * Time.deltaTime;

    if( Mathf.Abs( deltaAngle ) > Mathf.Abs( wheelAngle ) )
    {
    wheelAngle = 0f;
    return;
    }
    if( wheelAngle > 0f )
    wheelAngle -= deltaAngle;
    else
    wheelAngle += deltaAngle;
    }
    }
     
  11. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,865
    It's better that you create another script for speed handling. For example you can try this one (haven't tested it):

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class YOUR_SCRIPT_NAME : MonoBehaviour
    4. {
    5.    private int fingerId = -1;
    6.    public GUITexture speed;
    7.    public float speedupcar;
    8.  
    9.    void Update()
    10.    {
    11.      bool texturePressed = false;
    12.      
    13.      foreach( Touch t in Input.touches )
    14.      {
    15.        // don't allow more than one fingers on the texture
    16.        if( !texturePressed )
    17.        {
    18.          if( fingerId == -1 && t.phase == TouchPhase.Began && speed.HitTest( t.position ) )
    19.          {
    20.            fingerId = t.fingerId;
    21.            speedupcar += Time.deltaTime;
    22.            texturePressed = true;
    23.          }
    24.          else if( t.fingerId == touchId )
    25.          {
    26.            speedupcar += Time.deltaTime;
    27.            texturePressed = true;
    28.          }
    29.        }
    30.      }
    31.      
    32.      if( !texturePressed )
    33.        fingerId = -1;
    34.    }
    35. }
     
  12. herman111

    herman111

    Joined:
    May 11, 2014
    Posts:
    119
    Dude...thanks for a great script
     
  13. ravi83

    ravi83

    Joined:
    Jul 19, 2014
    Posts:
    5
    This script Work For me Thanks For The Help.
     
  14. ravi83

    ravi83

    Joined:
    Jul 19, 2014
    Posts:
    5
    there is one more issue. when i resize my game window in unity why this steering is out of the window. and when i use this script the wheel position is fix but it did't rotate.
    void OnGUI()
    {


    Vector2 ratio = new Vector2 (Screen.width / originalWidth, Screen.height / originalHeight);
    Matrix4x4 guiMatrix = Matrix4x4.identity;
    guiMatrix.SetTRS (new Vector3 (1, 1, 1), Quaternion.identity, new Vector3 (ratio.x, ratio.y, 1));
    GUI.matrix = guiMatrix;




    Matrix4x4 theMatrix = GUI.matrix;
    GUIUtility.RotateAroundPivot( wheelAngle, wheelPosition.center + deltaPivot );
    GUI.DrawTexture( wheelPosition, wheelTexture );
    GUI.matrix = theMatrix;
    GUI.matrix = Matrix4x4.identity;
    }
    }
     

    Attached Files:

    • 1st.jpg
      1st.jpg
      File size:
      145.5 KB
      Views:
      2,017
    • 2nd.jpg
      2nd.jpg
      File size:
      115.7 KB
      Views:
      1,653
  15. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,865
    I'm not sure what your script does (I'm not good at matrices). However I know why the wheel got out of the screen. The position of the wheel is only calculated at the Start function for better performance. Normally, your screen size shouldn't change run-time in a real device. So, I think it is OK like this. If you resize the window and then start the game, wheel should be fine.
     
    Last edited: Jul 21, 2014
  16. Adnan Ijaz

    Adnan Ijaz

    Joined:
    Sep 18, 2014
    Posts:
    1
    Thanks dear its really helpful for me :)
     
  17. FieroOfTheCanada

    FieroOfTheCanada

    Joined:
    Aug 9, 2014
    Posts:
    25
    This is great thanks so much for sharing this with us!!
     
  18. Nomibuilder

    Nomibuilder

    Joined:
    Apr 24, 2014
    Posts:
    20
    Thanks dear. :)
     
  19. Nomibuilder

    Nomibuilder

    Joined:
    Apr 24, 2014
    Posts:
    20
    Just One question. How can I access Getangle() function into my C# Code. I want it here.
    FrontLeftWheel.steerAngle =
     
  20. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,865
    If your SteeringWheel script is in a GameObject called "WheelObject", you should type this code:
    Code (CSharp):
    1. FrontLeftWheel.steerAngle = GameObject.Find( "WheelObject" ).GetComponent<SteeringWheel>().GetAngle();
    If both scripts are in the same GameObject, you can simply use this code:
    Code (CSharp):
    1. FrontLeftWheel.steerAngle = GetComponent<SteeringWheel>().GetAngle();
    If your compiler gives an error like SteeringWheel is unknown identifier, then try putting SteeringWheel script in a folder called "Plugins" (source: http://answers.unity3d.com/questions/48874/accessing-javascript-variable-from-c-and-vice-vers.html)

    For better performance, you can cache SteeringWheel component in a variable and use this variable to access the script (it is faster). Id est:
    Code (CSharp):
    1. private SteeringWheel wheelVariable;
    2.  
    3. void Start() {
    4. wheelVariable = GetComponent<SteeringWheel>();
    5. }
    Code (CSharp):
    1. FrontLeftWheel.steerAngle = wheelVariable.GetAngle();
    Note that GetAngle() function returns the angle of the steering wheel in degrees. If steerAngle variable expects a value between 0 and 1, then change the GetAngle() function like this:
    Code (CSharp):
    1. return wheelAngle / maximumAngle;
     
    Last edited: Oct 21, 2014
  21. Nomibuilder

    Nomibuilder

    Joined:
    Apr 24, 2014
    Posts:
    20
    Thank You so much .. it really helped :)
     
  22. djoshi

    djoshi

    Joined:
    Mar 28, 2014
    Posts:
    182
    Thanks for wonderful script. Its working but i am stuck at linking it to my car control.Can you help?
    I have car control script in which i have static function containing all input code. I want to pass your "wheelAngle" value in that function but i keep getting error "
    Assets/EdyVehiclePhysics/Scripts/CarMain.js(290,26): BCE0020: An instance of type 'CarMain' is required to access non static member 'steerAngle'."

    I understand that this is something to do with static and non static function but how to solve i dont know. Please help...

    My Static function is like :

    static function SendInput(Car : CarControl, reverseRequiresStop : boolean, brakeRelease : boolean) : boolean
    {
    // Obtener datos de la entrada
    #if MOBILE_INPUT
    var steerValue = steerAngle.wheelAngle;//Mathf.Clamp(CrossPlatformInput.GetAxis("Horizontal"), -1, 1);
    var forwardValue = Mathf.Clamp(CrossPlatformInput.GetAxis("Vertical"), 0, 1);
    var reverseValue = -1 * Mathf.Clamp(CrossPlatformInput.GetAxis("Vertical"), -1, 0);
    var handbrakeValue = Mathf.Clamp(CrossPlatformInput.GetAxis("Jump"), 0, 1);
    #else
    var steerValue = Mathf.Clamp(Input.GetAxis("Horizontal"), -1, 1);
    var forwardValue = Mathf.Clamp(Input.GetAxis("Vertical"), 0, 1);
    var reverseValue = -1 * Mathf.Clamp(Input.GetAxis("Vertical"), -1, 0);
    var handbrakeValue = Mathf.Clamp(Input.GetAxis("Jump"), 0, 1);
    #endif
     
  23. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,865
    Change these two lines

    Code (JavaScript):
    1. private var wheelAngle : float; // Wheel's angle in degrees
    2. public var maximumAngle : float = 500f; // Maximum angle the steering wheel can rotate
    like these:

    Code (JavaScript):
    1. public static var wheelAngle : float; // Wheel's angle in degrees
    2. public static var maximumAngle : float = 500f; // Maximum angle the steering wheel can rotate
    Let's say you named the steering wheel script as SteeringWheelScript. All you need to do is changing this line

    Code (JavaScript):
    1. var steerValue = steerAngle.wheelAngle;
    like this:

    Code (JavaScript):
    1. var steerValue = SteeringWheelScript.wheelAngle / SteeringWheelScript.maximumAngle;
    Hope it works.
     
  24. djoshi

    djoshi

    Joined:
    Mar 28, 2014
    Posts:
    182
    Thank for quick reply..

    No still getting that error

    my code in CarMain.Js script for more clearance...

    public var steeringObject : GameObject;
    private var steeringWheelScript : SteeringWheelScript;

    function Start()
    {
    steeringObject=GameObject.Find("Steering");
    steeringWheelScript=steeringObject.GetComponent(SteeringWheelScript);
    }

    static function SendInput(Car : CarControl, reverseRequiresStop : boolean, brakeRelease : boolean) : boolean
    {
    // Obtener datos de la entrada
    #if MOBILE_INPUT
    var steerValue =steeringWheelScript.wheelAngle / steeringWheelScript.maximumAngle;
    var forwardValue = Mathf.Clamp(CrossPlatformInput.GetAxis("Vertical"), 0, 1);
    var reverseValue = -1 * Mathf.Clamp(CrossPlatformInput.GetAxis("Vertical"), -1, 0);
    var handbrakeValue = Mathf.Clamp(CrossPlatformInput.GetAxis("Jump"), 0, 1);
    #else
    var steerValue = Mathf.Clamp(Input.GetAxis("Horizontal"), -1, 1);
    var forwardValue = Mathf.Clamp(Input.GetAxis("Vertical"), 0, 1);
    var reverseValue = -1 * Mathf.Clamp(Input.GetAxis("Vertical"), -1, 0);
    var handbrakeValue = Mathf.Clamp(Input.GetAxis("Jump"), 0, 1);
    #endif
     
    Last edited: Nov 26, 2014
  25. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,865
    Type "SteeringWheelScript.wheelAngle", not "steeringWheelScript.wheelAngle".
     
  26. djoshi

    djoshi

    Joined:
    Mar 28, 2014
    Posts:
    182
    Ohk..Superb thanks.. It worked..
    Now I am facing problem that car wheel turns reverse side to steer wheel..
    I tried wheelAngle = -wheelAngle; in update function but does not work properly..
     
  27. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,865
    Just fetch "-SteeringWheelScript.wheelAngle" instead of "SteeringWheelScript.wheelAngle" in your script.
     
  28. djoshi

    djoshi

    Joined:
    Mar 28, 2014
    Posts:
    182
    Great...Thanks for super script & your support..
     
  29. A-Tunga

    A-Tunga

    Joined:
    Jul 13, 2014
    Posts:
    13
    Thank Works Fine :) *Yasir hoca da buradaymış :D
     
    yasirkula likes this.
  30. nbg_yalta

    nbg_yalta

    Joined:
    Oct 3, 2012
    Posts:
    378
    Hi there, can someone implement this code to work with new UI?
     
  31. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,865
    Minor update! First of all thank you all for your interest in this script.

    With the update, I combined the two scripts (PC and Android scripts) into a single script. Now a single script supports both platforms.

    In addition:

    + GetAngle() now returns a value between -1 and 1 (both inclusive), just like Input.GetAxis(), rather than the angle of the steering wheel. This way, it is easier to implement the wheel in your car control scripts.
    + GetAngle() returns positive value when the wheel is rotated right, and it returns negative value when the wheel is rotated left (it was vice versa in the older version due to a bug)

    @nbg_yalta I may support UI later but I have some other plans right now. Still, if anyone would like to change the code to support the UI system, they are welcome!
     
  32. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,865
    New update!

    A (new) UI version of the code is added to the main post. It worked well on Unity editor but I haven't tested it on a mobile device. If you test it on a mobile device, please share the result here (also check if it supports multi-touch).

    Hope you like it :D
     
    Meceka likes this.
  33. Pharaoh35

    Pharaoh35

    Joined:
    Dec 25, 2012
    Posts:
    57
    Man, thanks!
     
  34. midliong

    midliong

    Joined:
    Oct 4, 2013
    Posts:
    7
    Hi,
    Thank you very much for this script.
    Can you help me to implement the get angle to rotate camera?
     
  35. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,865
    What exactly are you aiming to do?
     
  36. midliong

    midliong

    Joined:
    Oct 4, 2013
    Posts:
    7
    I try to use this script to rotate a steering wheel and rotate another object like camera, cube,etc.
    It works if the object gui but not working on 3d object.

    I try to modify your script and add game object and in update i try to feed the wheelangle to the object y transform. But unity always crash.

    NVM. somehow it works, i just need to restart unity, probably a bug.
     
    Last edited: Feb 13, 2015
    yasirkula likes this.
  37. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,865
    Alright; in case problem persists, you can contact me again.

    I'd like to remind you that writing something like "transform.eulerAngles.y = anAngle;" is wrong. If you are using transform.Rotate function or altering all three variables of transform.eulerAngles at once (like "transform.eulerAngles = Vector3.up * anAngle;" ), then it is OK.
     
  38. midliong

    midliong

    Joined:
    Oct 4, 2013
    Posts:
    7
    Sorry another question, how to make the getangle value back to 0 after full cycle?
    Let say i put maksimum angle of 360 and when it reach maksimum. the value get reset back to 0 so i can do another full cycle.
     
  39. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,865
    At the end of the DragEvent, you may add "wheelAngle = wheelAngle % 360f;". You may need to remove the line with the Clamp function.

    I don't know if it will work correctly as this was not my intention while creating this script.
     
  40. midliong

    midliong

    Joined:
    Oct 4, 2013
    Posts:
    7
    It works, thank you.
     
  41. uurr

    uurr

    Joined:
    Jan 9, 2015
    Posts:
    2
    Hi,sorry for disturb...
    i already created one script for car control but this is only control button. i just want to add steel wheel control.
    As you know,in order to button controller,i have wheel collider,and use FrontLeftWhell.steerAngle and unfortunately could not revise this script.
    Could you support me?
     
  42. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,865
    If you named the steering wheel script as SteeringWheel (and if both SteeringWheel and controller scripts are attached to the same GameObject), then your code should be like this:

    FrontLeftWhell.steerAngle = GetComponent(SteeringWheel).GetClampedValue();

    or (if you used the Legacy code):

    FrontLeftWhell.steerAngle = GetComponent(SteeringWheel).GetAngle();
     
    uurr likes this.
  43. uurr

    uurr

    Joined:
    Jan 9, 2015
    Posts:
    2
    Thank you,it's working :)
     
  44. prasanth-akon

    prasanth-akon

    Joined:
    May 30, 2013
    Posts:
    16
    Hello yasirkula,
    I'm using your script for Android steering wheel controller for my game. And it works absolutely fine. But i have some problem and i think only you can help me. The thing is i have to change the steering is position in runtime.(ie. Left and right screen steering.) Can you help me? Thanks in advance.
     
  45. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,865
    Hey there,

    I guess you are using the OnGUI code. To change the position of the wheel, all you need to do is change wheelPosition and then update wheelCenter accordingly. For example, to change the position from right side of the screen to left side of the screen, execute that code:

    Code (JavaScript):
    1. wheelPosition = new Rect( 75, Screen.height - wheelSize - 75, wheelSize, wheelSize );
    2. wheelCenter = new Vector2( wheelPosition.x + wheelPosition.width * 0.5f, Screen.height - wheelPosition.y - wheelPosition.height * 0.5f );
    To return to the right side of the screen:

    Code (JavaScript):
    1. wheelPosition = new Rect( Screen.width - wheelSize - 75, Screen.height - wheelSize - 75, wheelSize, wheelSize );
    2. wheelCenter = new Vector2( wheelPosition.x + wheelPosition.width * 0.5f, Screen.height - wheelPosition.y - wheelPosition.height * 0.5f );
     
  46. prasanth-akon

    prasanth-akon

    Joined:
    May 30, 2013
    Posts:
    16
    Hello,
    Actually i'm using the new 4.6 GUI
    Thank you
     
  47. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,865
    I don't really know how to do that. You can search for "how to reposition Unity UI by script". I am sure you will find some useful resources.
     
  48. wana7262

    wana7262

    Joined:
    Jul 2, 2012
    Posts:
    103
    what about NGUI? can you please change the code for NGUI support?
     
  49. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,865
    I don't use NGUI. Sadly, I can't do that.
     
  50. iamshaneturner

    iamshaneturner

    Joined:
    May 6, 2015
    Posts:
    3
    Hi there.

    This script has literally been a lifesaver.

    With a mouse, the wheel works perfectly, and follows the position of the pointer exactly.
    When I test it on my Android device, the steering wheel fails to keep up with the position of my finger, and never makes it further than a quarter of a turn before bugging out.

    I'm using the script as is, without any modifications.

    Thanks for your help!
    Regards
    Shane
     
    Last edited: May 6, 2015