Unity基础篇:Unity实现双击事件(奔跑,位移)。

有时候我们使用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;
            }
        }
    }
}

 

  • 6
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值