关于unity:黑魂复刻游戏的按键长按功能Unity随手记

明天实现的内容:
按键长按
长按是判断咱们按下一个按键的持续时间是否大于一个固定值,持续时间大于该值阐明以后咱们正在长按,在黑魂游戏中,玩家的翻滚/后跳和冲刺都是一个按键,区别在于长按该键是冲刺,短按就是翻滚/后跳。咱们仍然会用到计时器来实现按钮长按。

在按下按键后,咱们会开启delaying计时器,在delaying计时器执行期间按键的isDelaying信号会被设置为true。所以,按住按钮并且isDelaying为false表明按键为长按状态,松开按键并且isDelaying为true表明按键为短按。
下列代码为最新的MyButton。

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

// 自制按钮类
public class MyButton
{
    public float extendingDuration = 0.2f; //extending的工夫长度
    public float delayingDuration = 0.2f; //delaying的工夫长度

    public bool isPressing = false; //正在按压
    public bool onPressed = false; //刚刚按下
    public bool onRelease = false; //刚刚被开释
    public bool isDoubleClick = false; //双击
    public bool isLongPress = false; //长按
    public bool isShortPress = false; //长按

    public bool isExtending = false; //开释按键后的一段时间内为true 用于双击判断  
    public bool isDelaying = false; //刚刚按下后的一段时间内为true 用于长按判断

    private bool currentState = false; //以后状态
    private bool lastState = false; //上一帧的状态
    private MyTimer extendingTimer = new MyTimer(); //extending计时器
    private MyTimer delayingTimer = new MyTimer(); //delaying计时器

    // 更新MyButton
    public void Tick(bool _input)
    {
        extendingTimer.Tick(Time.deltaTime);
        delayingTimer.Tick(Time.deltaTime);

        onPressed = false; //OnPressd只有一种状况下是true 所以每次都先设置为false
        onRelease = false; //与OnPressed同理

        currentState = _input; //按键的以后状态永远和对应物理按键的状态统一

        isPressing = currentState; //是否被按下 按下就是true

        if (currentState != lastState) //判断按键信号是否扭转 扭转阐明刚刚按下按键或刚刚松开按键
        {
            if (currentState == true) //刚刚按下按键
            {
                onPressed = true;
                StartTimer(delayingTimer, delayingDuration);
            }
            else //刚刚松开按键
            {
                onRelease = true;
                StartTimer(extendingTimer, extendingDuration);
            }
        }

        lastState = currentState; //完结时将上一帧状态更新为以后帧状态

        isExtending = (extendingTimer.state == MyTimer.TIMER_STATE.RUN) ? true : false; //设置extending
        isDelaying = (delayingTimer.state == MyTimer.TIMER_STATE.RUN) ? true : false; //设置delaying

        isLongPress = (isPressing && !isDelaying) ? true : false; //长按判断
        isShortPress = (isDelaying && onRelease) ? true : false; //短按判断
        isDoubleClick = (isExtending && isPressing) ? true : false; //双击判断
    }

    private void StartTimer(MyTimer _timer, float _extDuration)
    {
        _timer.duration = _extDuration;
        _timer.Go();
    }
}

有了新的长按/短按信号,咱们就能够间接应用。

        // 翻滚/后跳
        jab_roll = buttonRun_jab_roll.isShortPress;
        // 冲刺
        run = buttonRun_jab_roll.isLongPress;

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理