首页 > 解决方案 > How do I stop and restart a looping animation when I use 'Input.GetKeyUp'?

问题描述

Basically; when the shift+w is pressed, the camera shake animation plays. The problem I am currently facing is; when I let go of the keys, the animation is frozen in its last state (this is tilting -3 to 3 on the x axis). This can freeze the camera's tilting and can be frozen diagonally.

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

public class CameraShake : MonoBehaviour
{
    private Animator myAnimator;
    private Animation myAnim;

    void Start()
    {
        myAnimator = GetComponent<Animator> ();
        myAnimator.enabled = false;
        myAnim = GetComponent<Animation> ();
        myAnim.enabled = false;
    }

    void Update () 
    {
        if (Input.GetKey (KeyCode.W)) 
        {
            if (Input.GetKeyDown (KeyCode.LeftShift)) 
            {
                myAnimator.enabled = true;
            }
        }
        if (Input.GetKey (KeyCode.LeftShift)) 
        {
            if (Input.GetKeyDown (KeyCode.W)) 
            {
                myAnimator.enabled = true;
            }
        }

        {
            if (Input.GetKeyUp (KeyCode.LeftShift)) 
            {
                myAnimator.enabled = false;
            }
            if (Input.GetKeyUp (KeyCode.W)) 
            {
                myAnimator.enabled = false;
            }
        }
    }
}

标签: c#unity3d

解决方案


不是禁用动画器,它会将动画冻结在原处,而是将速度设置为0f,然后将时间设置为0f

if (Input.GetKeyUp (KeyCode.LeftShift) 
    || Input.GetKeyUp (KeyCode.W)) 
{
     myAnimator.speed = 0f;
     myAnimator.Play("cshake",0,0f);
}

推荐阅读