Jason
Jason

Reputation: 452

How to manage animations?

I'm using C# and I'm currently building a 3rd person view game. I have a 3D character model with the animations in frames so I have to cut the animations by frame

The problem is I currently have 5 animations (idle, run, walk, punch, jump) and this is my code

void Update () {
    if (Input.GetAxis("Horizontal") != 0 || Input.GetAxis("Vertical") != 0){
        //play run animation
    } else {
        if (motion.x != 0 || motion.z != 0){
            motion.x = 0;
            motion.z = 0;
        }
                    //play idle anim
    }

    if (Input.GetKeyDown(KeyCode.Space) && controller.isGrounded){
    //play jump anim
    }

    if (Input.GetKeyDown(KeyCode.P)){
        //play punch anim
    }

    if (!controller.isGrounded){
        //play jump anim
    }

    vertVelo -= gravity * Time.deltaTime;
    motion.y = vertVelo;
    this.controller.Move(motion * Time.deltaTime);
}

The problem occurs when I press P to make the character punch. It seems the idle animation in the update function is being called so that the punch animation doesn't have time to play.

So, what's the solution? are there any animation managing technique or should I use delay?

Upvotes: 1

Views: 2596

Answers (2)

strobe
strobe

Reputation: 529

You may block idle animation while punch is playing (but may be it's not best approach):

bool isPunchPlaying = false;

void Update () {
    //... 
    if (!isPunchPlaying) {
        // Play idle anim
    }
    // ...
    if (Input.GetKeyDown(KeyCode.P)){
        //play punch anim
        isPunchPlaying = true;
        StartCoroutine(WaitThenDoPunch(animation["punch"].length));
    }
    // ...
}

IEnumerator WaitThenDoPunch(float time) {
    yield return new WaitForSeconds(time);
    isPunchPlaying = false;
}

Upvotes: 1

Whiplash450
Whiplash450

Reputation: 964

Try googling for animation layers in Unity and blending between animations.

You can set anim loops on a layer with higher layer numbers overriding lower layers.

This means that you can have the idle loop on say layer 1, and this plays continuously. Then say your jump loop is on layer 2. When the jump logic fires the jump loop, it plays once, then the idle loop continues.

This doc on 'AnimationState' in Unity could also be useful > link <

Upvotes: 0

Related Questions