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

6次阅读

共计 2026 个字符,预计需要花费 6 分钟才能阅读完成。

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

在按下按键后,咱们会开启 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;
正文完
 0