0
\$\begingroup\$

I am having difficulties here. I want to move my character with the buttons and I want the character to rotate wherever he is going.

Also I want to play an animation when there is no keys pressed. I am able to do that but I want the animation to play after 10 seconds of no key being pressed, and only once. Than after a movement that resets and again after 10 seconds of no key the animation plays. (The animation works but it happens right after I stop pressing a key and continuously.)

IEnumerator Test()
{
    yield return new WaitForSeconds(10.0f);
}

void Update()
{
    if (Input.GetKey(KeyCode.W))
    {
        counter += Time.deltaTime;
        transform.Translate((Vector3.forward) * moveSpeed * Time.deltaTime);
        Debug.Log("Pressing W key");
    }
    if (Input.GetKey(KeyCode.S))
    {
        counter += Time.deltaTime;
        transform.Translate((Vector3.back) * moveSpeed * Time.deltaTime);
        Debug.Log("Pressing s key");
    }
    if (Input.GetKey(KeyCode.A))
    {
        counter += Time.deltaTime;
        transform.Rotate(Vector3.down * rotateSpeed);
        Debug.Log("Pressing a key");
    }
    if (Input.GetKey(KeyCode.D))
    {
        counter += Time.deltaTime;
        transform.Rotate(Vector3.up * rotateSpeed);
        Debug.Log("pressed D");
    }
    if (!Input.GetMouseButton(1))
    {
        moveSpeed = 20;
    }

    if (!Input.anyKey)
    {
        if (counter >= 2)
        {
            StartCoroutine(Test());
            anim.Play("Animation");
            counter = 0;
            Debug.Log("A key or mouse click has been detected");
        }
    }
}
\$\endgroup\$
1
\$\begingroup\$

You can do it in a more simple way, like this:

float lastKeyPressedTime;

void Update()
{
    if(Input.anyKey )
         lastKeyPressedTime = Time.time;

    if(lastKeyPressedTime + 10f < Time.time ) 
    {
        PlayAnimation();
        lastKeyPressedTime = Time.time;
    }
}

About the animation, don't forget to uncheck the Loop checkbox in Inspector

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.