如何检测长按然后激活动画?

时间:2015-08-22 09:48:23

标签: c# animation unity3d

如何检测触摸屏上的长按然后激活动画?手指松开后,顺利播放另一个动画?让我们以Crossy Road中的主角为例:当用户按下时,鸡“蹲下”,当用户松开手指时,鸡会跳起来。同样的概念。 C#。

3 个答案:

答案 0 :(得分:1)

bool state;
bool calledLong;
float timer;
float timeForLongPress = 1;

void Update () {
    if (Input.GetMouseButtonDown (0)) {
        state = true;
        //Write here method you want to call instantly when user presses the button
    }
    if (state) {
        //Write here method you want to call whenever user is holding mouse button
        timer += Time.deltaTime;
        if (timer > timeForLongPress) {
            //Write here method you want to call EACH FRAME after user is holding mouse button for more than "timeForLongPress"
            if (!calledLong) {
                calledLong = true;
                //Write here method you want to call only ONCE after user is holding mouse button for more than "timeForLongPress"
            }
        }
    }
    if (Input.GetMouseButtonUp (0)) {
        timer = 0;
        calledLong = false;
        state = false;
    }
}

输入.GetMouseButtonUp(0),输入.GetMouseButtonDown(0)这是左键单击,右键单击只需将0更改为1,中间单击更改0到2。

如果您想要触摸(移动),只需更改

“Input.GetMouseButtonDown(0)”to“Input.touchCount> 0”

并更改

“Input.GetMouseButtonUp(0)”to“Input.touchCount == 0”

就是这样。

答案 1 :(得分:1)

您可以通过多种方式执行此操作,但您可以轻松尝试

Coroutine longPressCoroutine = null;
bool longPress = false;
void Update () {

    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
    {
        longPressCoroutine = StartCoroutine(PlayerAnimationAfterTime());
    }
    else if(Input.GetTouch(0).phase == TouchPhase.Ended)
    {
        if(longPressCoroutine != null)
        {
            StopCoroutine(longPressCoroutine);
            // if you want to play second animation only in case of longpress then use this 
            //check otherwise just play your animation here;
            if(longPress)
            {
                //play your second animation here
            }
            longPress = false;
        }
    }
}

IEnumerator PlayerAnimationAfterTime()
{
    yield return new WaitForSeconds(2f);
    //Play your first animation here;
    longPress = true;
}

答案 2 :(得分:0)

如果您不知道如何顺利​​更改动画,则需要查看Mecanim教程。这很简单。只是从第一个动画转换到第二个动画。并在检查员处设置此过渡的平滑度。

然后通过脚本触发第一个动画时按下。如果长按,则在释放时触发第二个。