How to change animator states from a key press?
I am working on a small beat-em-up game as a summer project. I am stuck trying to change the sprite animation when a key is pressed.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
Animator anim;
void Start()
{
anim = gameObject.GetComponent<Animator>();
}
void Update()
{
if (this.anim.GetCurrentAnimatorStateInfo(0).IsName("Jotaro Idle"))
{
if (Input.GetKey(KeyCode.D))
anim.SetTrigger("WalkRightfromIdle");
else if (Input.GetKey(KeyCode.A))
anim.SetTrigger("WalkLeftFromIdle");
}
}
}
Here is a screenshot of my animator window (each transition is controlled by a trigger) : https://imgur.com/a/f93GrAn
Any help would be appreciated.
Answer by chor64 · Jun 01, 2020 at 11:31 PM
Its easier to use a blend tree. Instead of individual triggers, in a blend tree, you use floats to indicate where to blend, that means that you can have all of the three animations in only one state.
To create a blend tree, right click and select "create blend tree". In the blend tree you can specify a float parameter and some animation clips. Create a float parameter and set the blend tree parameter to that. Add the idle and walk animations, then set the idle animation to have a blend value of 0f, then -1f for the left walk animation and 1f to the right walk animation.
And the script should be like this:
void Update()
{
if (Input.GetKey(KeyCode.D))
anim.SetFloat("YourBlendTreeFloat", 1f);
else if (Input.GetKey(KeyCode.A))
anim.SetFloat("YourBlendTreeFloat", -1f);
else
anim.SetFloat("YourBlendTreeFloat", 0f);
}
Your answer
Follow this Question
Related Questions
How to change animator states when a key is held through a C# script for a sprite? 0 Answers
Delay while using GetButtonDown and Animator 0 Answers
creating a 2d peeling system in unity 0 Answers
Calculate BoxCollider2D based on the actual player sprite 2 Answers
How do i make character eyes blink after some seconds have passed? (on 2D sprite) 1 Answer