黑魂复刻游戏的计时器类及按键双击功能——Unity随手记
今天实现的内容:
计时器类
计时器类,估计是个游戏都用得上。我们将专门实现一个计时器类,马上就会在实现按钮长按判断和双击判断中用上。
当时,设置计时器的duration,执行Go方法,计时器状态将在elapsedTime >= duration时从RUN变为FINISHED,计时器代码如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MyTimer { // 计时器的状态 public enum TIMER_STATE { IDLE, RUN, FINISHED } // 当前计时器的状态 public TIMER_STATE state; // duration秒之后计时器停止执行 public float duration = 1.0f; // 计时器执行的时间 public float elapsedTime; // 计时器更新方法 public void Tick(float _deltaTimer) { switch (state) { case TIMER_STATE.IDLE: break; case TIMER_STATE.RUN: elapsedTime += _deltaTimer; if (elapsedTime >= duration) state = TIMER_STATE.FINISHED; break; case TIMER_STATE.FINISHED: break; default: break; } } // 计时器开始执行 public void Go() { elapsedTime = 0; state = TIMER_STATE.RUN; } }
使用计时器类实现按键双击判断
给MyButton类新增信号IsExtending,当刚刚松开按键时,我们会开启计时器,在计时器执行期间,IsExtending会被设置为true。那么双击的逻辑就很清楚了,只要在IsExtending为true时按下了按键,就判断为双击。
下面的代码展示了添加了计时器用于设置Extending的MyButton类。要实现双击的代码还没有写出,可以在MyButton类中添加一个新的信号,或者在需要双击判断的地方查看当前isExtending和isPressing是否都为true。
using System.Collections; using System.Collections.Generic; using UnityEngine; // 自制按钮类 public class MyButton { public float extendingDuration = 0.2f; //按钮的双击/连击判定时长 public bool isPressing = false; //正在按压 public bool onPressed = false; //刚刚按下 public bool onRelease = false; //刚刚被释放 public bool isExtending = false; //释放按键后的一段时间内 private bool currentState = false; //当前状态 private bool lastState = false; //上一帧的状态 private MyTimer extendingTimer = new MyTimer(); //Extending计时器 // 更新MyButton public void Tick(bool _input) { onPressed = false; //OnPressd只有一种情况下是true 所以每次都先设置为false onRelease = false; //与OnPressed同理 currentState = _input; //按键的当前状态永远和对应物理按键的状态一致 isPressing = currentState; //是否被按下 按下就是true if (currentState != lastState) //判断是否刚刚按下按键或刚刚松开按键 { if (currentState == true) onPressed = true; else { onRelease = true; StartTimer(extendingTimer, extendingDuration); } } lastState = currentState; //结束时将上一帧状态更新为当前帧状态 isExtending = (extendingTimer.state == MyTimer.TIMER_STATE.RUN) ? true : false; //设置extending } private void StartTimer(MyTimer _timer, float _extDuration) { _timer.duration = _extDuration; _timer.Go(); } }