UNITY-如何对长单击和单击/双击执行不同的操作?

时间:2019-04-30 08:55:49

标签: unity3d position mouseevent collision onmousedown

因此,我正在制作一个2D角色控制器,如果按住鼠标(长按),玩家可以设置他要发射弹丸的方向,而当发射弹丸并与物体碰撞时,玩家可以设置该方向可以单击一次(或者最好单击两次)以将角色的位置替换为弹丸的位置。我正在尝试使用Input.onMouseButton和Input.onMouseButtonDown来做,但是我真的不知道。谢谢大家对我有帮助!

3 个答案:

答案 0 :(得分:0)

据我从文档和论坛中得知,您将需要使用Input.GetMouseButtonDown进行检查,以及自第一次按下以来经过的时间,例如so

答案 1 :(得分:0)

除了获取带有按钮的GetMouseButtonDown(int)之外,您还要跟踪记住检查按钮在哪个阶段。

TouchPhase

答案 2 :(得分:0)

对于长按,您只需要测量自第一次单击以来经过的时间。这是一个示例:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class LongClick : MonoBehaviour
{
    public float ClickDuration = 2;
    public UnityEvent OnLongClick;

    bool clicking = false;
    float totalDownTime = 0;


    // Update is called once per frame
    void Update()
    {
        // Detect the first click
        if (Input.GetMouseButtonDown(0))
        {
            totalDownTime = 0;
            clicking = true;
        }

        // If a first click detected, and still clicking,
        // measure the total click time, and fire an event
        // if we exceed the duration specified
        if (clicking && Input.GetMouseButton(0))
        {
            totalDownTime += Time.deltaTime;

            if (totalDownTime >= ClickDuration)
            {
                Debug.Log("Long click");
                clicking = false;
                OnLongClick.Invoke();
            }
        }

        // If a first click detected, and we release before the
        // duraction, do nothing, just cancel the click
        if (clicking && Input.GetMouseButtonUp(0))
        {
            clicking = false;
        }
    }
}

对于双击,您只需检查是否在指定的(短)间隔内再次单击:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class DoubleClick : MonoBehaviour
{
    public float DoubleClickInterval = 0.5f;
    public UnityEvent OnDoubleClick;

    float secondClickTimeout = -1;

    void Update()
    {

        if (Input.GetMouseButtonDown(0))
        {
            if (secondClickTimeout < 0)
            {
                // This is the first click, calculate the timeout
                secondClickTimeout = Time.time + DoubleClickInterval;
            }
            else
            {
                // This is the second click, is it within the interval 
                if (Time.time < secondClickTimeout)
                {
                    Debug.Log("Double click!");

                    // Invoke the event
                    OnDoubleClick.Invoke();

                    // Reset the timeout
                    secondClickTimeout = -1;
                }
            }

        }

        // If we wait too long for a second click, just cancel the double click
        if (secondClickTimeout > 0 && Time.time >= secondClickTimeout)
        {
            secondClickTimeout = -1;
        }

    }
}
相关问题