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

Convert keycode to ui button

Discussion in 'Scripting' started by Otavio_, Apr 21, 2018.

  1. Otavio_

    Otavio_

    Joined:
    Nov 3, 2017
    Posts:
    22
    I have 3 scripts that serve as a control for a helicopter to run, the problem is that I changed the project from pc to android, and I need to transfer these keyboard controls to gui, but I can't do that, and I do not even know if it's possible .
    I also tried to simulate the pressing of a key on the keyboard by pressing on the gui, but unity does not allow this.
    Anyway, can anyone give me any idea how to do this?

    This is the main thing.
    He's big but it's only in the end that he has the useful part, I put it all together just so that someone needs to use it or have a base.

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3.  
    4. public class HelicopterController : MonoBehaviour
    5. {
    6.     public AudioSource HelicopterSound;
    7.     public ControlPanel ControlPanel;
    8.     public Rigidbody HelicopterModel;
    9.     public HeliRotorController MainRotorController;
    10.     public HeliRotorController SubRotorController;
    11.  
    12.     public float TurnForce = 3f;
    13.     public float ForwardForce = 10f;
    14.     public float ForwardTiltForce = 20f;
    15.     public float TurnTiltForce = 30f;
    16.     public float EffectiveHeight = 100f;
    17.  
    18.     public float turnTiltForcePercent = 1.5f;
    19.     public float turnForcePercent = 1.3f;
    20.  
    21.     private float _engineForce;
    22.     public float EngineForce
    23.     {
    24.         get { return _engineForce; }
    25.         set
    26.         {
    27.             MainRotorController.RotarSpeed = value * 80;
    28.             SubRotorController.RotarSpeed = value * 40;
    29.             HelicopterSound.pitch = Mathf.Clamp(value / 40, 0, 1.2f);
    30.             if (UIGameController.runtime.EngineForceView != null)
    31.                 UIGameController.runtime.EngineForceView.text = string.Format("Engine value [ {0} ] ", (int)value);
    32.  
    33.             _engineForce = value;
    34.         }
    35.     }
    36.  
    37.     private Vector2 hMove = Vector2.zero;
    38.     private Vector2 hTilt = Vector2.zero;
    39.     private float hTurn = 0f;
    40.     public bool IsOnGround = true;
    41.  
    42.     // Use this for initialization
    43.    void Start ()
    44.    {
    45.         ControlPanel.KeyPressed += OnKeyPressed;
    46.    }
    47.  
    48.    void Update () {
    49.    }
    50.  
    51.     void FixedUpdate()
    52.     {
    53.         LiftProcess();
    54.         MoveProcess();
    55.         TiltProcess();
    56.     }
    57.  
    58.     private void MoveProcess()
    59.     {
    60.         var turn = TurnForce * Mathf.Lerp(hMove.x, hMove.x * (turnTiltForcePercent - Mathf.Abs(hMove.y)), Mathf.Max(0f, hMove.y));
    61.         hTurn = Mathf.Lerp(hTurn, turn, Time.fixedDeltaTime * TurnForce);
    62.         HelicopterModel.AddRelativeTorque(0f, hTurn * HelicopterModel.mass, 0f);
    63.         HelicopterModel.AddRelativeForce(Vector3.forward * Mathf.Max(0f, hMove.y * ForwardForce * HelicopterModel.mass));
    64.     }
    65.  
    66.     private void LiftProcess()
    67.     {
    68.         var upForce = 1 - Mathf.Clamp(HelicopterModel.transform.position.y / EffectiveHeight, 0, 1);
    69.         upForce = Mathf.Lerp(0f, EngineForce, upForce) * HelicopterModel.mass;
    70.         HelicopterModel.AddRelativeForce(Vector3.up * upForce);
    71.     }
    72.  
    73.     private void TiltProcess()
    74.     {
    75.         hTilt.x = Mathf.Lerp(hTilt.x, hMove.x * TurnTiltForce, Time.deltaTime);
    76.         hTilt.y = Mathf.Lerp(hTilt.y, hMove.y * ForwardTiltForce, Time.deltaTime);
    77.         HelicopterModel.transform.localRotation = Quaternion.Euler(hTilt.y, HelicopterModel.transform.localEulerAngles.y, -hTilt.x);
    78.     }
    79.  
    80.     private void OnKeyPressed(PressedKeyCode[] obj)
    81.     {
    82.         float tempY = 0;
    83.         float tempX = 0;
    84.  
    85.         // stable forward
    86.         if (hMove.y > 0)
    87.             tempY = - Time.fixedDeltaTime;
    88.         else
    89.             if (hMove.y < 0)
    90.                 tempY = Time.fixedDeltaTime;
    91.  
    92.         // stable lurn
    93.         if (hMove.x > 0)
    94.             tempX = -Time.fixedDeltaTime;
    95.         else
    96.             if (hMove.x < 0)
    97.                 tempX = Time.fixedDeltaTime;
    98.  
    99.  
    100.         foreach (var pressedKeyCode in obj)
    101.         {
    102.             switch (pressedKeyCode)
    103.             {
    104.                 case PressedKeyCode.SpeedUpPressed:
    105.  
    106.                     EngineForce += 0.1f;
    107.                     break;
    108.                
    109.                
    110.                
    111.                
    112.                
    113.                 case PressedKeyCode.SpeedDownPressed:
    114.  
    115.                     EngineForce -= 0.12f;
    116.                     if (EngineForce < 0) EngineForce = 0;
    117.                     break;
    118.  
    119.                    
    120.                    
    121.                    
    122.                    
    123.                    
    124.                     case PressedKeyCode.ForwardPressed:
    125.  
    126.                     if (IsOnGround) break;
    127.                     tempY = Time.fixedDeltaTime;
    128.                     break;
    129.                    
    130.                    
    131.                    
    132.                    
    133.                    
    134.                     case PressedKeyCode.BackPressed:
    135.  
    136.                     if (IsOnGround) break;
    137.                     tempY = -Time.fixedDeltaTime;
    138.                     break;
    139.                    
    140.                    
    141.                    
    142.                    
    143.                    
    144.                     case PressedKeyCode.LeftPressed:
    145.  
    146.                     if (IsOnGround) break;
    147.                     tempX = -Time.fixedDeltaTime;
    148.                     break;
    149.                    
    150.                    
    151.                    
    152.                    
    153.                    
    154.                     case PressedKeyCode.RightPressed:
    155.  
    156.                     if (IsOnGround) break;
    157.                     tempX = Time.fixedDeltaTime;
    158.                     break;
    159.                    
    160.                    
    161.                    
    162.                    
    163.                    
    164.                     case PressedKeyCode.TurnRightPressed:
    165.                     {
    166.                         if (IsOnGround) break;
    167.                         var force = (turnForcePercent - Mathf.Abs(hMove.y))*HelicopterModel.mass;
    168.                         HelicopterModel.AddRelativeTorque(0f, force, 0);
    169.                     }
    170.                     break;
    171.                    
    172.                    
    173.                    
    174.                    
    175.                    
    176.                     case PressedKeyCode.TurnLeftPressed:
    177.                     {
    178.                         if (IsOnGround) break;
    179.                        
    180.                         var force = -(turnForcePercent - Mathf.Abs(hMove.y))*HelicopterModel.mass;
    181.                         HelicopterModel.AddRelativeTorque(0f, force, 0);
    182.                     }
    183.                     break;
    184.  
    185.             }
    186.         }
    187.  
    188.         hMove.x += tempX;
    189.         hMove.x = Mathf.Clamp(hMove.x, -1, 1);
    190.  
    191.         hMove.y += tempY;
    192.         hMove.y = Mathf.Clamp(hMove.y, -1, 1);
    193.  
    194.     }
    195.  
    196.     private void OnCollisionEnter()
    197.     {
    198.         IsOnGround = true;
    199.     }
    200.  
    201.     private void OnCollisionExit()
    202.     {
    203.         IsOnGround = false;
    204.     }
    205. }
    Code (CSharp):
    1. using System;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class ControlPanel : MonoBehaviour {
    6.     public AudioSource MusicSound;
    7.  
    8.     [SerializeField]
    9.     KeyCode SpeedUp = KeyCode.Space;
    10.     [SerializeField]
    11.     KeyCode SpeedDown = KeyCode.C;
    12.     [SerializeField]
    13.     KeyCode Forward = KeyCode.W;
    14.     [SerializeField]
    15.     KeyCode Back = KeyCode.S;
    16.     [SerializeField]
    17.     KeyCode Left = KeyCode.A;
    18.     [SerializeField]
    19.     KeyCode Right = KeyCode.D;
    20.     [SerializeField]
    21.     KeyCode TurnLeft = KeyCode.Q;
    22.     [SerializeField]
    23.     KeyCode TurnRight = KeyCode.E;
    24.     [SerializeField]
    25.     KeyCode MusicOffOn = KeyCode.M;
    26.    
    27.     private KeyCode[] keyCodes;
    28.  
    29.     public Action<PressedKeyCode[]> KeyPressed;
    30.     private void Awake()
    31.     {
    32.         keyCodes = new[] {
    33.                             SpeedUp,
    34.                             SpeedDown,
    35.                             Forward,
    36.                             Back,
    37.                             Left,
    38.                             Right,
    39.                             TurnLeft,
    40.                             TurnRight
    41.                         };
    42.  
    43.     }
    44.  
    45.     void Start () {
    46.  
    47.    }
    48.  
    49.    void FixedUpdate ()
    50.    {
    51.        var pressedKeyCode = new List<PressedKeyCode>();
    52.        for (int index = 0; index < keyCodes.Length; index++)
    53.        {
    54.            var keyCode = keyCodes[index];
    55.            if (Input.GetKey(keyCode))
    56.                 pressedKeyCode.Add((PressedKeyCode)index);
    57.        }
    58.  
    59.        if (KeyPressed != null)
    60.            KeyPressed(pressedKeyCode.ToArray());
    61.  
    62.         // for test
    63.         if (Input.GetKey(MusicOffOn))
    64.         {
    65.            if (  MusicSound.volume == 1) return;
    66. /*            if (MusicSound.isPlaying)
    67.                 MusicSound.Stop();
    68.             else*/
    69.                 MusicSound.volume = 1;
    70.                 MusicSound.Play();
    71.         }
    72.      
    73.    }
    74. }
    Code (CSharp):
    1. public enum PressedKeyCode
    2. {
    3.     SpeedUpPressed,
    4.     SpeedDownPressed,
    5.     ForwardPressed,
    6.     BackPressed,
    7.     LeftPressed,
    8.     RightPressed,
    9.     TurnLeftPressed,
    10.     TurnRightPressed
    11. }
    Thanks to anyone who can help me. <3
     
  2. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    I think you may want touch control. There are tutorials for it on youtube.
     
    Otavio_ likes this.
  3. Otavio_

    Otavio_

    Joined:
    Nov 3, 2017
    Posts:
    22
    I already have the touch control, i just wanna know how can i link the controls on the script.
     
  4. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    Where's your touch code?
     
    Otavio_ likes this.
  5. Otavio_

    Otavio_

    Joined:
    Nov 3, 2017
    Posts:
    22
    I use the mobile controls from standart assests with their scritps

    Code (CSharp):
    1. using System;
    2. using UnityEngine;
    3. using UnityEngine.EventSystems;
    4.  
    5. namespace UnityStandardAssets.CrossPlatformInput
    6. {
    7.     public class Joystick : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler
    8.     {
    9.         public enum AxisOption
    10.         {
    11.             // Options for which axes to use
    12.             Both, // Use both
    13.             OnlyHorizontal, // Only horizontal
    14.             OnlyVertical // Only vertical
    15.         }
    16.  
    17.         public int MovementRange = 100;
    18.         public AxisOption axesToUse = AxisOption.Both; // The options for the axes that the still will use
    19.         public string horizontalAxisName = "Horizontal"; // The name given to the horizontal axis for the cross platform input
    20.         public string verticalAxisName = "Vertical"; // The name given to the vertical axis for the cross platform input
    21.  
    22.         Vector3 m_StartPos;
    23.         bool m_UseX; // Toggle for using the x axis
    24.         bool m_UseY; // Toggle for using the Y axis
    25.         CrossPlatformInputManager.VirtualAxis m_HorizontalVirtualAxis; // Reference to the joystick in the cross platform input
    26.         CrossPlatformInputManager.VirtualAxis m_VerticalVirtualAxis; // Reference to the joystick in the cross platform input
    27.  
    28.         void OnEnable()
    29.         {
    30.             CreateVirtualAxes();
    31.         }
    32.  
    33.         void Start()
    34.         {
    35.             m_StartPos = transform.position;
    36.         }
    37.  
    38.         void UpdateVirtualAxes(Vector3 value)
    39.         {
    40.             var delta = m_StartPos - value;
    41.             delta.y = -delta.y;
    42.             delta /= MovementRange;
    43.             if (m_UseX)
    44.             {
    45.                 m_HorizontalVirtualAxis.Update(-delta.x);
    46.             }
    47.  
    48.             if (m_UseY)
    49.             {
    50.                 m_VerticalVirtualAxis.Update(delta.y);
    51.             }
    52.         }
    53.  
    54.         void CreateVirtualAxes()
    55.         {
    56.             // set axes to use
    57.             m_UseX = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyHorizontal);
    58.             m_UseY = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyVertical);
    59.  
    60.             // create new axes based on axes to use
    61.             if (m_UseX)
    62.             {
    63.                 m_HorizontalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(horizontalAxisName);
    64.                 CrossPlatformInputManager.RegisterVirtualAxis(m_HorizontalVirtualAxis);
    65.             }
    66.             if (m_UseY)
    67.             {
    68.                 m_VerticalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(verticalAxisName);
    69.                 CrossPlatformInputManager.RegisterVirtualAxis(m_VerticalVirtualAxis);
    70.             }
    71.         }
    72.  
    73.  
    74.         public void OnDrag(PointerEventData data)
    75.         {
    76.             Vector3 newPos = Vector3.zero;
    77.  
    78.             if (m_UseX)
    79.             {
    80.                 int delta = (int)(data.position.x - m_StartPos.x);
    81.                 delta = Mathf.Clamp(delta, - MovementRange, MovementRange);
    82.                 newPos.x = delta;
    83.             }
    84.  
    85.             if (m_UseY)
    86.             {
    87.                 int delta = (int)(data.position.y - m_StartPos.y);
    88.                 delta = Mathf.Clamp(delta, -MovementRange, MovementRange);
    89.                 newPos.y = delta;
    90.             }
    91.             transform.position = new Vector3(m_StartPos.x + newPos.x, m_StartPos.y + newPos.y, m_StartPos.z + newPos.z);
    92.             UpdateVirtualAxes(transform.position);
    93.         }
    94.  
    95.  
    96.         public void OnPointerUp(PointerEventData data)
    97.         {
    98.             transform.position = m_StartPos;
    99.             UpdateVirtualAxes(m_StartPos);
    100.         }
    101.  
    102.  
    103.         public void OnPointerDown(PointerEventData data) { }
    104.  
    105.         void OnDisable()
    106.         {
    107.             // remove the joysticks from the cross platform input
    108.             if (m_UseX)
    109.             {
    110.                 m_HorizontalVirtualAxis.Remove();
    111.             }
    112.             if (m_UseY)
    113.             {
    114.                 m_VerticalVirtualAxis.Remove();
    115.             }
    116.         }
    117.     }
    118. }
    Code (CSharp):
    1. using System;
    2. #if UNITY_EDITOR
    3. using UnityEditor;
    4. #endif
    5. using UnityEngine;
    6.  
    7.  
    8. namespace UnityStandardAssets.CrossPlatformInput
    9. {
    10.     [ExecuteInEditMode]
    11.     public class MobileControlRig : MonoBehaviour
    12. #if UNITY_EDITOR
    13.         , UnityEditor.Build.IActiveBuildTargetChanged
    14. #endif
    15.     {
    16.         // this script enables or disables the child objects of a control rig
    17.         // depending on whether the USE_MOBILE_INPUT define is declared.
    18.  
    19.         // This define is set or unset by a menu item that is included with
    20.         // the Cross Platform Input package.
    21.  
    22.  
    23. #if !UNITY_EDITOR
    24.     void OnEnable()
    25.     {
    26.         CheckEnableControlRig();
    27.     }
    28. #else
    29.         public int callbackOrder
    30.         {
    31.             get
    32.             {
    33.                 return 1;
    34.             }
    35.         }
    36. #endif
    37.  
    38.         private void Start()
    39.         {
    40. #if UNITY_EDITOR
    41.             if (Application.isPlaying) //if in the editor, need to check if we are playing, as start is also called just after exiting play
    42. #endif
    43.             {
    44.                 UnityEngine.EventSystems.EventSystem system = GameObject.FindObjectOfType<UnityEngine.EventSystems.EventSystem>();
    45.  
    46.                 if (system == null)
    47.                 {//the scene have no event system, spawn one
    48.                     GameObject o = new GameObject("EventSystem");
    49.  
    50.                     o.AddComponent<UnityEngine.EventSystems.EventSystem>();
    51.                     o.AddComponent<UnityEngine.EventSystems.StandaloneInputModule>();
    52.                 }
    53.             }
    54.         }
    55.  
    56. #if UNITY_EDITOR
    57.  
    58.         private void OnEnable()
    59.         {
    60.             EditorApplication.update += Update;
    61.         }
    62.  
    63.  
    64.         private void OnDisable()
    65.         {
    66.             EditorApplication.update -= Update;
    67.         }
    68.  
    69.  
    70.         private void Update()
    71.         {
    72.             CheckEnableControlRig();
    73.         }
    74. #endif
    75.  
    76.  
    77.         private void CheckEnableControlRig()
    78.         {
    79. #if MOBILE_INPUT
    80.         EnableControlRig(true);
    81.         #else
    82.             EnableControlRig(false);
    83. #endif
    84.         }
    85.  
    86.  
    87.         private void EnableControlRig(bool enabled)
    88.         {
    89.             foreach (Transform t in transform)
    90.             {
    91.                 t.gameObject.SetActive(enabled);
    92.             }
    93.         }
    94.  
    95. #if UNITY_EDITOR
    96.         public void OnActiveBuildTargetChanged(BuildTarget previousTarget, BuildTarget newTarget)
    97.         {
    98.             CheckEnableControlRig();
    99.         }
    100. #endif
    101.     }
    102. }
    103.  
     
    Last edited: Apr 21, 2018
  6. rakkarage

    rakkarage

    Joined:
    Feb 3, 2014
    Posts:
    683
  7. Otavio_

    Otavio_

    Joined:
    Nov 3, 2017
    Posts:
    22
    akankshakhode990 likes this.
  8. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    A couple of ideas come to mind. Both involve getting your UI buttons to call methods. The first idea is that you call methods directly, doing the same work that your code is doing now when it cycles through any keys that are present.
    The other option is similar, but the method just records a specific keycode (unique to the button). You'd clear this list at the beginning of each update cycle, fill it up on any click(s) per update, and fire your event.
     
    Otavio_ likes this.
  9. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    There's a tutorial here for getting joystick and button input:
    I would keep the joystick, that's the equivalent of 4 buttons. You still probably have too many, it will cover up too much of the screen I think. I don't know if they let you use a joystick on each side, but that would help.
     
    Last edited: Apr 22, 2018
    Otavio_ likes this.
  10. Otavio_

    Otavio_

    Joined:
    Nov 3, 2017
    Posts:
    22
    Can you give me a little example of how i can call a method in my script? So I will could do the rest, and thanks for the ideia! :D (I know the part in the unity, like the "on click" function and set the public void there, but, i don't know where i have to put the method to be call in the script)
     
    soulaymanoboy likes this.
  11. Otavio_

    Otavio_

    Joined:
    Nov 3, 2017
    Posts:
    22
    Yeah, i already saw this video, and now, i just need to know how my joysticks will call the method in my script.
     
  12. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Say you have a script on GameObject A.

    On the button's OnClick, you drag that game object into the slot and you'll then have a drop down list of options. One of the options will be the script in question, and when you choose that you can choose a method on the script.
     
    Otavio_ likes this.
  13. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    I would skip all the key pressed stuff. Go to this line:
    foreach (var pressedKeyCode in obj){
    }
    Instead, use if, and else if to get the equivalent from the joystick.
    if(virtualjoystick.GetAxis("Vertical" )> 0){
    //do what button did
    }

    Make a copy of the script first, though. Those would have to be called in an update. I don't know if they are now.
    Otherwise, you can replace the button array with a boolean array and have the virtual joystick input in the update change the bool value, but I would just use the direct approach myself.
     
    Last edited: Apr 22, 2018
    Otavio_ likes this.
  14. Otavio_

    Otavio_

    Joined:
    Nov 3, 2017
    Posts:
    22
    Thank you guys, i will try to do this. :)
     
  15. ikrama312

    ikrama312

    Joined:
    May 6, 2019
    Posts:
    1
  16. Omoesiri

    Omoesiri

    Joined:
    Nov 16, 2016
    Posts:
    1
    Did you fix it. I am using the exact script Ive only been able to get Engine speed control to touch.
     
  17. hashammuhammad148

    hashammuhammad148

    Joined:
    Feb 19, 2021
    Posts:
    6
    just add ispressed script and replace the keycode with is pressed
    use this script:and replace controlpanel script with this control panel

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class pressedButton : MonoBehaviour
    {
    public bool isPressed;
    public string buttName;
    public void presse()
    {
    isPressed = true;

    }
    public void unpresse()
    {
    isPressed = false;

    }

    }


    using System;
    using System.Collections.Generic;
    using UnityEngine;

    public class ControlPanel : MonoBehaviour
    {
    public AudioSource MusicSound;

    public pressedButton SpeedUp;
    public pressedButton SpeedDown;
    public pressedButton Forward;
    public pressedButton Back;
    public pressedButton Left;
    public pressedButton Right;
    public pressedButton TurnLeft;
    public pressedButton TurnRight;
    public pressedButton MusicOffOn;

    private pressedButton[] keyCodes;

    public Action<PressedKeyCode[]> KeyPressed;
    private void Awake()
    {
    keyCodes = new[] {
    SpeedUp,
    SpeedDown,
    Forward,
    Back,
    Left,
    Right,
    TurnLeft,
    TurnRight
    };

    }

    void Start()
    {

    }

    void FixedUpdate()
    {
    var pressedKeyCode = new List<PressedKeyCode>();
    for (int index = 0; index < keyCodes.Length; index++)
    {
    var keyCode = keyCodes[index];
    if (keyCode.isPressed)
    pressedKeyCode.Add((PressedKeyCode)index);
    }

    if (KeyPressed != null)
    KeyPressed(pressedKeyCode.ToArray());

    // for test
    //if (Input.GetKey(MusicOffOn))
    //{
    // if (MusicSound.volume == 1) return;
    // /* if (MusicSound.isPlaying)
    // MusicSound.Stop();
    // else*/
    // MusicSound.volume = 1;
    // MusicSound.Play();
    //}

    }
    }