Logitech方向盘的拦截输入Unity

发布于 2025-02-11 20:51:53 字数 10483 浏览 0 评论 0原文

我是使用Unity和Logitech方向盘构建应用程序的。现在,我应该拦截方向盘上的按下按钮,并在场景中增加或减少滑块。我可以做到这一点,但是如果我尝试单击方向盘上的一个按钮,则该方法被调用一些。因此,这是代码:

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

namespace DrivingTest
{
    public class FearTest : MonoBehaviour
    {
        //public GameObject redDot;
        //public TextMeshPro textAnsia2;
        //public TextMesh textAnsia3;
        public GameObject consoleFearTest;
        public Slider slider;
        
        public int shouldFearTest = 0; // 0 - false, 1 - true
        public int secondsInterval;
        //public int secondsToDisaply;
        public int reactionTestDuration;

        private float endTime;
        private float dotDisaplyAtTime;
        private List<float> fearTestValue = new List<float>();
        private int missedSignals;

        private int currentDotsCount;
        private bool isReactionAlreadyGiven;

        public bool ShouldFearTest
        {
            get
            {
                return shouldFearTest != 0;
            }
        }
        
        void OnEnable()
        {
            GameManager.TestSceneLoaded += OnSceneLoaded;
        }

        private void OnDisable()
        {
            GameManager.TestSceneLoaded -= OnSceneLoaded;
        }

        #region Scene Loaded

        private void OnSceneLoaded(eTESTS test)
        {
            if (SceneManager.GetActiveScene().name != test.ToString())
                return;

            Reset();
            GetApiParams();
        }

        public void Disabler()
        {
            //qui posso recuperare il valore del ansia selezionata.
            //text.SetActive(false);
        }

        #endregion

        private void GetApiParams()
        {
#if UNITY_EDITOR
            if (!GameManager.Instance)
            {
                Init();
                return;
            }
#endif
            Debug.Log("called fearTest");
            NextTestOutput nextTestOutput = GameManager.Instance.currentTest;
            if (nextTestOutput.content != null && nextTestOutput.content.Count > 0)
            {
                foreach (var item in nextTestOutput.content[0].listInputParameter)
                {
                    switch ((ePARAMETERS)item.id)
                    {
                        case ePARAMETERS.FEAR:
                            shouldFearTest = System.Convert.ToInt32(item.Value);
                            break;

                        case ePARAMETERS.DURATION_OF_TEST:
                            reactionTestDuration = System.Convert.ToInt32(item.Value);
                            break;

                        case ePARAMETERS.REPEAT_FEAR:
                            secondsInterval = System.Convert.ToInt32(item.Value);
                            break;
                    }
                }
                Debug.Log("called fearTest "+ ShouldFearTest);
                if (ShouldFearTest)
                {
                    Init();
                }
            }
        }

        Coroutine displayCoroutine;

        public void Init()
        {
            endTime = Time.time + reactionTestDuration + 10;
            SetRedDotSize();
            displayCoroutine = StartCoroutine(RedDotDisplay());
        }

        private IEnumerator RedDotDisplay()
        {
            yield return new WaitForSeconds(2);

            while (true)
            {
                SetRandomDotPosition();
                ShowSlider(true);
                isReactionAlreadyGiven = false;
                dotDisaplyAtTime = Time.time;
                currentDotsCount++;
                //yield return new WaitForSeconds(secondsToDisaply);

                if(!isReactionAlreadyGiven)
                {
                    missedSignals++;
                }
                //RedDot(false);
                if ((reactionTestDuration > 0 && endTime <= Time.time))
                    break;

                float waitTime = secondsInterval;// - secondsToDisaply;
                yield return new WaitForSeconds(waitTime);
            }
        }

        private void Update()
        {
            if (!ShouldFearTest)
                return;
            /* for (int i = 0; i < 129; i++)
             {
                 if (LogitechGSDK.LogiButtonIsPressed(0, i))
                     Debug.Log("Pulsante " + i + " premuto: ");
                     Debug.Log("Pulsante " + i + " premuto: ");

             }*/

            /*     foreach (KeyCode vKey in System.Enum.GetValues(typeof(KeyCode)))
                 {
                     if (Input.GetKey(vKey))
                     {
                         //your code here
                         Debug.Log("Premuto pulsante  " + vKey);
                     }
                 }*/
            
            for (int i = 0; i < 30; i++)
            {
                if (LogitechGSDK.LogiIsConnected(0) && LogitechGSDK.LogiButtonIsPressed(0, i))
                {
                    //isReactionAlreadyGiven = true;
                   
                }
            }
            //HO PREMUTO LA ROTELLA VERSO DESTRA
            if (!isReactionAlreadyGiven && consoleFearTest.activeSelf && (LogitechGSDK.LogiIsConnected(0) && LogitechGSDK.LogiButtonIsPressed(0, 21)))
            {
                isReactionAlreadyGiven = true;
                int sliderValue = (int)slider.value;
                if (sliderValue < 9)
                    sliderValue++;
                slider.value = sliderValue;
                //float reactionTime = Time.time - dotDisaplyAtTime;
                Debug.Log("Fear Test valore impostato: " + sliderValue);
                //ShowSlider(false);
                //dotDisplayReactTime.Add(reactionTime);
                isReactionAlreadyGiven = false;
            }
            //HO PREMUTO LA ROTELLA VERSO SINISTRA
            if (!isReactionAlreadyGiven && consoleFearTest.activeSelf && (LogitechGSDK.LogiIsConnected(0) && LogitechGSDK.LogiButtonIsPressed(0, 22)))
            {
                isReactionAlreadyGiven = true;
                int sliderValue = (int)slider.value;
                if (sliderValue > 0)
                    sliderValue--;
                slider.value = sliderValue;
                //float reactionTime = Time.time - dotDisaplyAtTime;
                Debug.Log("Fear Test valore impostato: " + sliderValue);
                // ShowSlider(false);
                //dotDisplayReactTime.Add(reactionTime);
                isReactionAlreadyGiven = false;
            }
            if (!isReactionAlreadyGiven && consoleFearTest.activeSelf && (LogitechGSDK.LogiIsConnected(0) && LogitechGSDK.LogiButtonIsPressed(0, 23)))
            {
                //isReactionAlreadyGiven = true;
                //float reactionTime = Time.time - dotDisaplyAtTime;
                int sliderValue = (int)slider.value;
                Debug.Log("Fear Test : " + sliderValue);
                ShowSlider(false);
                fearTestValue.Add(sliderValue);
            }
        }

        /*public double GetReactionTimeAvg()
        {
            double avg = 0;
            foreach (var item in dotDisplayReactTime)
            {
                avg += item;
            }
            //avg / currentDotsCount
            return avg / (float)dotDisplayReactTime.Count;
        }*/

        public double GetMissedSignals()
        {
            return ((float) missedSignals / (float) currentDotsCount) * 100;
        }

        private void ShowSlider(bool state)
        {
            //redDot.SetActive(state);
            consoleFearTest.SetActive(state);
        }

        private void SetRedDotSize()
        {
            //redDot.transform.localScale *= dotRadius;
            //textAnsia2.transform.localScale *= dotRadius;
            //textAnsia3.transform.localScale *= dotRadius;
        }

        private void SetRandomDotPosition()
        {
            Vector3 pos2 = new Vector3(500, 500, 0);
            Debug.Log("text ansia 2 : " + pos2);
            consoleFearTest.transform.position = pos2;
            //text.transform.position = pos;
        }

        #region Getting Red Dot b/w 2 cricles

        /*
         Code from : https://gist.github.com/Ashwinning/89fa09b3aa3de4fd72c946a874b77658
        */

        /// <summary>
        /// Returns a random point in the space between two concentric circles.
        /// </summary>
        /// <param name="minRadius"></param>
        /// <param name="maxRadius"></param>
        /// <returns></returns>
        Vector3 GetRandomPointBetweenTwoCircles(float minRadius, float maxRadius)
        {
            //Get a point on a unit circle (radius = 1) by normalizing a random point inside unit circle.
            Vector3 randomUnitPoint = Random.insideUnitCircle.normalized;
            //Now get a random point between the corresponding points on both the circles
            return GetRandomVector3Between(randomUnitPoint * minRadius, randomUnitPoint * maxRadius);
        }

        /// <summary>
        /// Returns a random vector3 between min and max. (Inclusive)
        /// </summary>
        /// <returns>The <see cref="UnityEngine.Vector3"/>.</returns>
        /// <param name="min">Minimum.</param>
        /// <param name="max">Max.</param>
        Vector3 GetRandomVector3Between(Vector3 min, Vector3 max)
        {
            return min + Random.Range(0, 1) * (max - min);
        }

        #endregion

        #region Reset

        private void Reset()
        {
            if (displayCoroutine != null)
                StopCoroutine(displayCoroutine);

            ShowSlider(false);
            shouldFearTest = 0;
            reactionTestDuration = 0;
            secondsInterval = 0;
            missedSignals = 0;
            endTime = 0;
            dotDisaplyAtTime = 0;
            fearTestValue.Clear();
            //redDot.transform.localScale = Vector3.one;
            //textAnsia2.transform.localScale = Vector3.one;
            //textAnsia3.transform.localScale = Vector3.one;
            currentDotsCount = 0;
            isReactionAlreadyGiven = false;
        }
        #endregion

    }
}

我认为我错误使用更新方法来拦截单击方向盘。我该如何修复?

I m building the application using Unity and Logitech Steering Wheel. Now I should to intercept the press button on Steering wheel and increase or decreare a Slider in the Scene. I can do this but if I try to click a button on steering wheel the method is called some times. So this is the code:

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

namespace DrivingTest
{
    public class FearTest : MonoBehaviour
    {
        //public GameObject redDot;
        //public TextMeshPro textAnsia2;
        //public TextMesh textAnsia3;
        public GameObject consoleFearTest;
        public Slider slider;
        
        public int shouldFearTest = 0; // 0 - false, 1 - true
        public int secondsInterval;
        //public int secondsToDisaply;
        public int reactionTestDuration;

        private float endTime;
        private float dotDisaplyAtTime;
        private List<float> fearTestValue = new List<float>();
        private int missedSignals;

        private int currentDotsCount;
        private bool isReactionAlreadyGiven;

        public bool ShouldFearTest
        {
            get
            {
                return shouldFearTest != 0;
            }
        }
        
        void OnEnable()
        {
            GameManager.TestSceneLoaded += OnSceneLoaded;
        }

        private void OnDisable()
        {
            GameManager.TestSceneLoaded -= OnSceneLoaded;
        }

        #region Scene Loaded

        private void OnSceneLoaded(eTESTS test)
        {
            if (SceneManager.GetActiveScene().name != test.ToString())
                return;

            Reset();
            GetApiParams();
        }

        public void Disabler()
        {
            //qui posso recuperare il valore del ansia selezionata.
            //text.SetActive(false);
        }

        #endregion

        private void GetApiParams()
        {
#if UNITY_EDITOR
            if (!GameManager.Instance)
            {
                Init();
                return;
            }
#endif
            Debug.Log("called fearTest");
            NextTestOutput nextTestOutput = GameManager.Instance.currentTest;
            if (nextTestOutput.content != null && nextTestOutput.content.Count > 0)
            {
                foreach (var item in nextTestOutput.content[0].listInputParameter)
                {
                    switch ((ePARAMETERS)item.id)
                    {
                        case ePARAMETERS.FEAR:
                            shouldFearTest = System.Convert.ToInt32(item.Value);
                            break;

                        case ePARAMETERS.DURATION_OF_TEST:
                            reactionTestDuration = System.Convert.ToInt32(item.Value);
                            break;

                        case ePARAMETERS.REPEAT_FEAR:
                            secondsInterval = System.Convert.ToInt32(item.Value);
                            break;
                    }
                }
                Debug.Log("called fearTest "+ ShouldFearTest);
                if (ShouldFearTest)
                {
                    Init();
                }
            }
        }

        Coroutine displayCoroutine;

        public void Init()
        {
            endTime = Time.time + reactionTestDuration + 10;
            SetRedDotSize();
            displayCoroutine = StartCoroutine(RedDotDisplay());
        }

        private IEnumerator RedDotDisplay()
        {
            yield return new WaitForSeconds(2);

            while (true)
            {
                SetRandomDotPosition();
                ShowSlider(true);
                isReactionAlreadyGiven = false;
                dotDisaplyAtTime = Time.time;
                currentDotsCount++;
                //yield return new WaitForSeconds(secondsToDisaply);

                if(!isReactionAlreadyGiven)
                {
                    missedSignals++;
                }
                //RedDot(false);
                if ((reactionTestDuration > 0 && endTime <= Time.time))
                    break;

                float waitTime = secondsInterval;// - secondsToDisaply;
                yield return new WaitForSeconds(waitTime);
            }
        }

        private void Update()
        {
            if (!ShouldFearTest)
                return;
            /* for (int i = 0; i < 129; i++)
             {
                 if (LogitechGSDK.LogiButtonIsPressed(0, i))
                     Debug.Log("Pulsante " + i + " premuto: ");
                     Debug.Log("Pulsante " + i + " premuto: ");

             }*/

            /*     foreach (KeyCode vKey in System.Enum.GetValues(typeof(KeyCode)))
                 {
                     if (Input.GetKey(vKey))
                     {
                         //your code here
                         Debug.Log("Premuto pulsante  " + vKey);
                     }
                 }*/
            
            for (int i = 0; i < 30; i++)
            {
                if (LogitechGSDK.LogiIsConnected(0) && LogitechGSDK.LogiButtonIsPressed(0, i))
                {
                    //isReactionAlreadyGiven = true;
                   
                }
            }
            //HO PREMUTO LA ROTELLA VERSO DESTRA
            if (!isReactionAlreadyGiven && consoleFearTest.activeSelf && (LogitechGSDK.LogiIsConnected(0) && LogitechGSDK.LogiButtonIsPressed(0, 21)))
            {
                isReactionAlreadyGiven = true;
                int sliderValue = (int)slider.value;
                if (sliderValue < 9)
                    sliderValue++;
                slider.value = sliderValue;
                //float reactionTime = Time.time - dotDisaplyAtTime;
                Debug.Log("Fear Test valore impostato: " + sliderValue);
                //ShowSlider(false);
                //dotDisplayReactTime.Add(reactionTime);
                isReactionAlreadyGiven = false;
            }
            //HO PREMUTO LA ROTELLA VERSO SINISTRA
            if (!isReactionAlreadyGiven && consoleFearTest.activeSelf && (LogitechGSDK.LogiIsConnected(0) && LogitechGSDK.LogiButtonIsPressed(0, 22)))
            {
                isReactionAlreadyGiven = true;
                int sliderValue = (int)slider.value;
                if (sliderValue > 0)
                    sliderValue--;
                slider.value = sliderValue;
                //float reactionTime = Time.time - dotDisaplyAtTime;
                Debug.Log("Fear Test valore impostato: " + sliderValue);
                // ShowSlider(false);
                //dotDisplayReactTime.Add(reactionTime);
                isReactionAlreadyGiven = false;
            }
            if (!isReactionAlreadyGiven && consoleFearTest.activeSelf && (LogitechGSDK.LogiIsConnected(0) && LogitechGSDK.LogiButtonIsPressed(0, 23)))
            {
                //isReactionAlreadyGiven = true;
                //float reactionTime = Time.time - dotDisaplyAtTime;
                int sliderValue = (int)slider.value;
                Debug.Log("Fear Test : " + sliderValue);
                ShowSlider(false);
                fearTestValue.Add(sliderValue);
            }
        }

        /*public double GetReactionTimeAvg()
        {
            double avg = 0;
            foreach (var item in dotDisplayReactTime)
            {
                avg += item;
            }
            //avg / currentDotsCount
            return avg / (float)dotDisplayReactTime.Count;
        }*/

        public double GetMissedSignals()
        {
            return ((float) missedSignals / (float) currentDotsCount) * 100;
        }

        private void ShowSlider(bool state)
        {
            //redDot.SetActive(state);
            consoleFearTest.SetActive(state);
        }

        private void SetRedDotSize()
        {
            //redDot.transform.localScale *= dotRadius;
            //textAnsia2.transform.localScale *= dotRadius;
            //textAnsia3.transform.localScale *= dotRadius;
        }

        private void SetRandomDotPosition()
        {
            Vector3 pos2 = new Vector3(500, 500, 0);
            Debug.Log("text ansia 2 : " + pos2);
            consoleFearTest.transform.position = pos2;
            //text.transform.position = pos;
        }

        #region Getting Red Dot b/w 2 cricles

        /*
         Code from : https://gist.github.com/Ashwinning/89fa09b3aa3de4fd72c946a874b77658
        */

        /// <summary>
        /// Returns a random point in the space between two concentric circles.
        /// </summary>
        /// <param name="minRadius"></param>
        /// <param name="maxRadius"></param>
        /// <returns></returns>
        Vector3 GetRandomPointBetweenTwoCircles(float minRadius, float maxRadius)
        {
            //Get a point on a unit circle (radius = 1) by normalizing a random point inside unit circle.
            Vector3 randomUnitPoint = Random.insideUnitCircle.normalized;
            //Now get a random point between the corresponding points on both the circles
            return GetRandomVector3Between(randomUnitPoint * minRadius, randomUnitPoint * maxRadius);
        }

        /// <summary>
        /// Returns a random vector3 between min and max. (Inclusive)
        /// </summary>
        /// <returns>The <see cref="UnityEngine.Vector3"/>.</returns>
        /// <param name="min">Minimum.</param>
        /// <param name="max">Max.</param>
        Vector3 GetRandomVector3Between(Vector3 min, Vector3 max)
        {
            return min + Random.Range(0, 1) * (max - min);
        }

        #endregion

        #region Reset

        private void Reset()
        {
            if (displayCoroutine != null)
                StopCoroutine(displayCoroutine);

            ShowSlider(false);
            shouldFearTest = 0;
            reactionTestDuration = 0;
            secondsInterval = 0;
            missedSignals = 0;
            endTime = 0;
            dotDisaplyAtTime = 0;
            fearTestValue.Clear();
            //redDot.transform.localScale = Vector3.one;
            //textAnsia2.transform.localScale = Vector3.one;
            //textAnsia3.transform.localScale = Vector3.one;
            currentDotsCount = 0;
            isReactionAlreadyGiven = false;
        }
        #endregion

    }
}

I think that I wrong use Update method to intercept click on Steering wheel. How can I fixed it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文