其他分享
首页 > 其他分享> > 黑魂复刻游戏的按键长按功能——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;

 

标签:isDelaying,false,Unity,黑魂,bool,按键,true,public,复刻
来源: https://www.cnblogs.com/heyu123/p/14893825.html