Simple 2D sprite animator code :(
So i totally figured this would be easy code. I'm trying to use a sprite i made and animate it running around a more isometric landscape, so i need it to move in all directions.
I wanted to make it run when i pressed the WASD keys and flip when i changed direction from A-D.
For some reason when i press the WASD keys, it takes mashing the buttons a few times to get the trigger to actually set!
It's like it wants to work so bad, but it needs a push.
here's my code:
Controller script:
public class PlayerController : MonoBehaviour { private float speed;
private void Start()
{
speed = 1;
}
private void Update()
{
//SpriteRenderer spriteRenderer = gameObject.GetComponent<SpriteRenderer>();
float axisX = Input.GetAxisRaw("Horizontal");
float axisY = Input.GetAxisRaw("Vertical");
transform.Translate(new Vector3(axisX, axisY) * Time.deltaTime * speed);
}
}
Animator script:
Animator anim;
// Use this for initialization
void Start () {
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
if (Input.anyKey == false)
{
anim.SetTrigger("PlayerBase");
}
if (Input.GetKeyDown(KeyCode.W))
{
anim.SetTrigger("PlayerRun");
}
if (Input.GetKeyDown(KeyCode.A))
{
anim.SetTrigger("PlayerRun");
}
if (Input.GetKeyDown(KeyCode.S))
{
anim.SetTrigger("PlayerRun");
}
if (Input.GetKeyDown(KeyCode.D))
{
anim.SetTrigger("PlayerRun");
}
}
}
Answer by cj-carey · Sep 07, 2018 at 01:41 AM
I'd suggest watching the animator tab when animations are changing to see if it has exit time on the transitions. You can flip a setting called "Has Exit Time". Also there's also a "transition duration" parameter. Check this question for more info on exit time and transition duration
Another suggestion of mine is that you try changing
if (Input.anyKey == false)
{
anim.SetTrigger("PlayerBase");
}
into
if (Input.anyKeyDown == false)
{
anim.SetTrigger("PlayerBase");
}
The way you have it with anyKey means that the trigger will be called over and over when no keys are being pressed. Depending on how you set up your states, maybe that's actually what you want, but I figured I'd throw that out there. .