有时候我们使用Unity设计游戏需要对游戏对象双击让他执行特殊操作,比如奔跑,位移之类的的。实现方法很简单,核心语句是
if (Input.GetKeyDown(KeyCode.W))
{
t2 = Time.realtimeSinceStartup;
if (t2 - t1 < 0.2f)
{
if(Input.GetKey(KeyCode.W))
{
run = true;
}
}
t1 = t2;
}
之后其余的功能可以根据自己的需求添加,下面是个小Demo,供大家参考。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour {
double timeVal = 0.2f; //设置冷却时间,从上一次奔跑到下一次奔跑有0.2s冷却,同时解决了刚跑完抬起W键短时间再次按下W会继续跑的问题。
bool run = false;
bool walkFlag = false;
double t1;
double t2;
void FixedUpdate()
{
if (Input.GetKeyDown(KeyCode.W)&& walkFlag == false)
{
t2 = Time.realtimeSinceStartup;
if (t2 - t1 < 0.2f)
{
if(Input.GetKey(KeyCode.W))
{
run = true;
}
Debug.Log("双击");
}
t1 = t2;
}
else if(walkFlag == true)
{
timeVal -= Time.fixedDeltaTime;
if(timeVal<=0)
{
walkFlag = false;
}
if (walkFlag == false)
{
timeVal = 0.2f;
}
}
if (!run)
{
if (Input.GetKey(KeyCode.W))
{
Debug.Log("Walking");
}
if (Input.GetKeyUp(KeyCode.W))
{
Debug.Log("Stopping");
}
}
if (run)
{
if (Input.GetKey(KeyCode.W))
{
Debug.Log("Running");
}
if(Input.GetKeyUp(KeyCode.W))
{
Debug.Log("Stopping");
run = false;
walkFlag = true;
}
}
}
}