Successional key pressed detection

Problem to be solved :

Need to detect whether the player has pressed the specified key successionally to invoke 'running' animation.


Solution :

Record the time when the first and second time the key is pressed.
Check if their difference (in absolute) is smaller than 0.5

    // successional key pressed detection viriable
    float FirstPressTime = -100; // time for first press key
    float SecondPressTime = 100; // time for second press key
    private bool FirstPress = false; // bool variable used for successional key pressed detection

    void WalkAndRun()
    {
        if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            bool onechance = false; // only one chance for each press, in case it records both first and second press


            StartWalking(); // start walking on key down

            if (FirstPress == false) // 
            {
                FirstPressTime = Time.time;
                FirstPress = true;
                onechance = true;

                Debug.Log("FP" + FirstPressTime);
            }

            if (FirstPress == true && onechance == false) { 
                SecondPressTime = Time.time;
                FirstPress = false;

                Debug.Log("SP" + SecondPressTime);
            }
            if (Mathf.Abs(SecondPressTime - FirstPressTime) < 0.5f)
                StartRunning();
            else
            { }
        }
        
        if (Input.GetKeyUp(KeyCode.RightArrow))
        {
            StopWalking();
            StopRunning();
        }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,470评论 0 23
  • 1 时间复杂度概述 当一个程序产生的时候,就自然而然产生了执行时间,我们不可能每次都去一个一个运行进行比较。于是一...
    KaelQ阅读 15,169评论 3 24
  • 今天已经是2017年1月10日了,这篇文章本该在1月1日之前出炉,可惜本人拖延症晚期,规划了很久,直到今天才动手写...
    球球爱次鱼阅读 1,761评论 0 0
  • Dear Doris, Thanks foryour great well-done outline for ou...
    启春阅读 1,105评论 0 0
  • 那些物,那些景,曾经的过眼而入漫不经心有意无意的一切,多年后的重遇,激起的没有暖心的感慨和物是人非的感触,只有对现...
    离江混子阅读 1,462评论 0 1