Convert keycode to ui button

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.

using UnityEngine;
using UnityEngine.UI;

public class HelicopterController : MonoBehaviour
{
    public AudioSource HelicopterSound;
    public ControlPanel ControlPanel;
    public Rigidbody HelicopterModel;
    public HeliRotorController MainRotorController;
    public HeliRotorController SubRotorController;

    public float TurnForce = 3f;
    public float ForwardForce = 10f;
    public float ForwardTiltForce = 20f;
    public float TurnTiltForce = 30f;
    public float EffectiveHeight = 100f;

    public float turnTiltForcePercent = 1.5f;
    public float turnForcePercent = 1.3f;

    private float _engineForce;
    public float EngineForce
    {
        get { return _engineForce; }
        set
        {
            MainRotorController.RotarSpeed = value * 80;
            SubRotorController.RotarSpeed = value * 40;
            HelicopterSound.pitch = Mathf.Clamp(value / 40, 0, 1.2f);
            if (UIGameController.runtime.EngineForceView != null)
                UIGameController.runtime.EngineForceView.text = string.Format("Engine value [ {0} ] ", (int)value);

            _engineForce = value;
        }
    }

    private Vector2 hMove = Vector2.zero;
    private Vector2 hTilt = Vector2.zero;
    private float hTurn = 0f;
    public bool IsOnGround = true;

    // Use this for initialization
   void Start ()
   {
        ControlPanel.KeyPressed += OnKeyPressed;
   }

   void Update () {
   }
 
    void FixedUpdate()
    {
        LiftProcess();
        MoveProcess();
        TiltProcess();
    }

    private void MoveProcess()
    {
        var turn = TurnForce * Mathf.Lerp(hMove.x, hMove.x * (turnTiltForcePercent - Mathf.Abs(hMove.y)), Mathf.Max(0f, hMove.y));
        hTurn = Mathf.Lerp(hTurn, turn, Time.fixedDeltaTime * TurnForce);
        HelicopterModel.AddRelativeTorque(0f, hTurn * HelicopterModel.mass, 0f);
        HelicopterModel.AddRelativeForce(Vector3.forward * Mathf.Max(0f, hMove.y * ForwardForce * HelicopterModel.mass));
    }

    private void LiftProcess()
    {
        var upForce = 1 - Mathf.Clamp(HelicopterModel.transform.position.y / EffectiveHeight, 0, 1);
        upForce = Mathf.Lerp(0f, EngineForce, upForce) * HelicopterModel.mass;
        HelicopterModel.AddRelativeForce(Vector3.up * upForce);
    }

    private void TiltProcess()
    {
        hTilt.x = Mathf.Lerp(hTilt.x, hMove.x * TurnTiltForce, Time.deltaTime);
        hTilt.y = Mathf.Lerp(hTilt.y, hMove.y * ForwardTiltForce, Time.deltaTime);
        HelicopterModel.transform.localRotation = Quaternion.Euler(hTilt.y, HelicopterModel.transform.localEulerAngles.y, -hTilt.x);
    }

    private void OnKeyPressed(PressedKeyCode[] obj)
    {
        float tempY = 0;
        float tempX = 0;

        // stable forward
        if (hMove.y > 0)
            tempY = - Time.fixedDeltaTime;
        else
            if (hMove.y < 0)
                tempY = Time.fixedDeltaTime;

        // stable lurn
        if (hMove.x > 0)
            tempX = -Time.fixedDeltaTime;
        else
            if (hMove.x < 0)
                tempX = Time.fixedDeltaTime;


        foreach (var pressedKeyCode in obj)
        {
            switch (pressedKeyCode)
            {
                case PressedKeyCode.SpeedUpPressed:

                    EngineForce += 0.1f;
                    break;
               
               
               
               
               
                case PressedKeyCode.SpeedDownPressed:

                    EngineForce -= 0.12f;
                    if (EngineForce < 0) EngineForce = 0;
                    break;

                   
                   
                   
                   
                   
                    case PressedKeyCode.ForwardPressed:

                    if (IsOnGround) break;
                    tempY = Time.fixedDeltaTime;
                    break;
                   
                   
                   
                   
                   
                    case PressedKeyCode.BackPressed:

                    if (IsOnGround) break;
                    tempY = -Time.fixedDeltaTime;
                    break;
                   
                   
                   
                   
                   
                    case PressedKeyCode.LeftPressed:

                    if (IsOnGround) break;
                    tempX = -Time.fixedDeltaTime;
                    break;
                   
                   
                   
                   
                   
                    case PressedKeyCode.RightPressed:

                    if (IsOnGround) break;
                    tempX = Time.fixedDeltaTime;
                    break;
                   
                   
                   
                   
                   
                    case PressedKeyCode.TurnRightPressed:
                    {
                        if (IsOnGround) break;
                        var force = (turnForcePercent - Mathf.Abs(hMove.y))*HelicopterModel.mass;
                        HelicopterModel.AddRelativeTorque(0f, force, 0);
                    }
                    break;
                   
                   
                   
                   
                   
                    case PressedKeyCode.TurnLeftPressed:
                    {
                        if (IsOnGround) break;
                       
                        var force = -(turnForcePercent - Mathf.Abs(hMove.y))*HelicopterModel.mass;
                        HelicopterModel.AddRelativeTorque(0f, force, 0);
                    }
                    break;

            }
        }

        hMove.x += tempX;
        hMove.x = Mathf.Clamp(hMove.x, -1, 1);

        hMove.y += tempY;
        hMove.y = Mathf.Clamp(hMove.y, -1, 1);

    }

    private void OnCollisionEnter()
    {
        IsOnGround = true;
    }

    private void OnCollisionExit()
    {
        IsOnGround = false;
    }
}
using System;
using System.Collections.Generic;
using UnityEngine;

public class ControlPanel : MonoBehaviour {
    public AudioSource MusicSound;

    [SerializeField]
    KeyCode SpeedUp = KeyCode.Space;
    [SerializeField]
    KeyCode SpeedDown = KeyCode.C;
    [SerializeField]
    KeyCode Forward = KeyCode.W;
    [SerializeField]
    KeyCode Back = KeyCode.S;
    [SerializeField]
    KeyCode Left = KeyCode.A;
    [SerializeField]
    KeyCode Right = KeyCode.D;
    [SerializeField]
    KeyCode TurnLeft = KeyCode.Q;
    [SerializeField]
    KeyCode TurnRight = KeyCode.E;
    [SerializeField]
    KeyCode MusicOffOn = KeyCode.M;
   
    private KeyCode[] 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 (Input.GetKey(keyCode))
                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();
        }
     
   }
}
public enum PressedKeyCode
{
    SpeedUpPressed,
    SpeedDownPressed,
    ForwardPressed,
    BackPressed,
    LeftPressed,
    RightPressed,
    TurnLeftPressed,
    TurnRightPressed
}

Thanks to anyone who can help me. <3

I think you may want touch control. There are tutorials for it on youtube.

1 Like

I already have the touch control, i just wanna know how can i link the controls on the script.

Where’s your touch code?

1 Like

I use the mobile controls from standart assests with their scritps

using System;
using UnityEngine;
using UnityEngine.EventSystems;

namespace UnityStandardAssets.CrossPlatformInput
{
    public class Joystick : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler
    {
        public enum AxisOption
        {
            // Options for which axes to use
            Both, // Use both
            OnlyHorizontal, // Only horizontal
            OnlyVertical // Only vertical
        }

        public int MovementRange = 100;
        public AxisOption axesToUse = AxisOption.Both; // The options for the axes that the still will use
        public string horizontalAxisName = "Horizontal"; // The name given to the horizontal axis for the cross platform input
        public string verticalAxisName = "Vertical"; // The name given to the vertical axis for the cross platform input

        Vector3 m_StartPos;
        bool m_UseX; // Toggle for using the x axis
        bool m_UseY; // Toggle for using the Y axis
        CrossPlatformInputManager.VirtualAxis m_HorizontalVirtualAxis; // Reference to the joystick in the cross platform input
        CrossPlatformInputManager.VirtualAxis m_VerticalVirtualAxis; // Reference to the joystick in the cross platform input

        void OnEnable()
        {
            CreateVirtualAxes();
        }

        void Start()
        {
            m_StartPos = transform.position;
        }

        void UpdateVirtualAxes(Vector3 value)
        {
            var delta = m_StartPos - value;
            delta.y = -delta.y;
            delta /= MovementRange;
            if (m_UseX)
            {
                m_HorizontalVirtualAxis.Update(-delta.x);
            }

            if (m_UseY)
            {
                m_VerticalVirtualAxis.Update(delta.y);
            }
        }

        void CreateVirtualAxes()
        {
            // set axes to use
            m_UseX = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyHorizontal);
            m_UseY = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyVertical);

            // create new axes based on axes to use
            if (m_UseX)
            {
                m_HorizontalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(horizontalAxisName);
                CrossPlatformInputManager.RegisterVirtualAxis(m_HorizontalVirtualAxis);
            }
            if (m_UseY)
            {
                m_VerticalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(verticalAxisName);
                CrossPlatformInputManager.RegisterVirtualAxis(m_VerticalVirtualAxis);
            }
        }


        public void OnDrag(PointerEventData data)
        {
            Vector3 newPos = Vector3.zero;

            if (m_UseX)
            {
                int delta = (int)(data.position.x - m_StartPos.x);
                delta = Mathf.Clamp(delta, - MovementRange, MovementRange);
                newPos.x = delta;
            }

            if (m_UseY)
            {
                int delta = (int)(data.position.y - m_StartPos.y);
                delta = Mathf.Clamp(delta, -MovementRange, MovementRange);
                newPos.y = delta;
            }
            transform.position = new Vector3(m_StartPos.x + newPos.x, m_StartPos.y + newPos.y, m_StartPos.z + newPos.z);
            UpdateVirtualAxes(transform.position);
        }


        public void OnPointerUp(PointerEventData data)
        {
            transform.position = m_StartPos;
            UpdateVirtualAxes(m_StartPos);
        }


        public void OnPointerDown(PointerEventData data) { }

        void OnDisable()
        {
            // remove the joysticks from the cross platform input
            if (m_UseX)
            {
                m_HorizontalVirtualAxis.Remove();
            }
            if (m_UseY)
            {
                m_VerticalVirtualAxis.Remove();
            }
        }
    }
}
using System;
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;


namespace UnityStandardAssets.CrossPlatformInput
{
    [ExecuteInEditMode]
    public class MobileControlRig : MonoBehaviour
#if UNITY_EDITOR
        , UnityEditor.Build.IActiveBuildTargetChanged
#endif
    {
        // this script enables or disables the child objects of a control rig
        // depending on whether the USE_MOBILE_INPUT define is declared.

        // This define is set or unset by a menu item that is included with
        // the Cross Platform Input package.


#if !UNITY_EDITOR
    void OnEnable()
    {
        CheckEnableControlRig();
    }
#else
        public int callbackOrder
        {
            get
            {
                return 1;
            }
        }
#endif

        private void Start()
        {
#if UNITY_EDITOR
            if (Application.isPlaying) //if in the editor, need to check if we are playing, as start is also called just after exiting play
#endif
            {
                UnityEngine.EventSystems.EventSystem system = GameObject.FindObjectOfType<UnityEngine.EventSystems.EventSystem>();

                if (system == null)
                {//the scene have no event system, spawn one
                    GameObject o = new GameObject("EventSystem");

                    o.AddComponent<UnityEngine.EventSystems.EventSystem>();
                    o.AddComponent<UnityEngine.EventSystems.StandaloneInputModule>();
                }
            }
        }

#if UNITY_EDITOR

        private void OnEnable()
        {
            EditorApplication.update += Update;
        }


        private void OnDisable()
        {
            EditorApplication.update -= Update;
        }


        private void Update()
        {
            CheckEnableControlRig();
        }
#endif


        private void CheckEnableControlRig()
        {
#if MOBILE_INPUT
        EnableControlRig(true);
        #else
            EnableControlRig(false);
#endif
        }


        private void EnableControlRig(bool enabled)
        {
            foreach (Transform t in transform)
            {
                t.gameObject.SetActive(enabled);
            }
        }

#if UNITY_EDITOR
        public void OnActiveBuildTargetChanged(BuildTarget previousTarget, BuildTarget newTarget)
        {
            CheckEnableControlRig();
        }
#endif
    }
}
1 Like

I need to change from keycode to gui button and not the opposite, but, thank you anyway.

1 Like

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.

1 Like

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.

1 Like

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! :smile: (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)

1 Like

Yeah, i already saw this video, and now, i just need to know how my joysticks will call the method in my script.

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.

1 Like

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.

1 Like

Thank you guys, i will try to do this. :slight_smile:

Try this. This is perfect. Control Freak 2 - Touch Input Made Easy! - Free Download | Dev Asset Collection

1 Like

Did you fix it. I am using the exact script Ive only been able to get Engine speed control to touch.

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();
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();
//}

}
}