I’m trying to write code for a top-down RPG player’s walking animation that moves up, down, left, and right.
And I’m having trouble trying to get the last player movement with a vector variable, but everytime I do that it only stores only one of the points, so if I’m going up-right it doesn’t store (1,1) but only (1,0)
I know this code is only messy so I’m open to suggestions to make it neater or better. Thank you.
using System.Collections;
using System.Collections.Generic;
using UnityEditor.U2D;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private Animator anim;
private Rigidbody2D rb;
private SpriteRenderer sprite;
private enum AnimationState { idleDown, walkingDown, idleUp, walkingUp, walkingXIdle, walkingX }
private float dirX;
private float dirY;
public float lastDirX = 0.0f;
public float lastDirY = 0.0f;
public Vector2 moveDir;
public Vector2 lastDir;
[SerializeField] private float moveSpeed = 10.0f;
private void Awake()
{
anim = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
sprite = GetComponent<SpriteRenderer>();
}
private void Update()
{
dirX = Input.GetAxisRaw("Horizontal");
dirY = Input.GetAxisRaw("Vertical");
moveDir = new Vector2(dirX, dirY);
if (moveDir != Vector2.zero)
{
lastDir = moveDir;
}
UpdateAnimationState();
}
private void FixedUpdate()
{
rb.velocity = new Vector2(dirX * moveSpeed, dirY * moveSpeed);
}
private void UpdateAnimationState()
{
AnimationState state;
if (moveDir.y < 0.0f && moveDir.x == 0.0f)
{
state = AnimationState.walkingDown;
}
else if (moveDir.y > 0.0f && moveDir.x == 0.0f)
{
state = AnimationState.walkingUp;
}
else if (lastDir == new Vector2(0.0f, 1.0f) && moveDir == Vector2.zero)
{
state = AnimationState.idleUp;
}
else if ((moveDir.x > 0.0f && moveDir.y > 0.0f) || (moveDir.x > 0.0f && moveDir.y < 0.0f) || (moveDir.x > 0.0f && moveDir.y == 0.0f)) // Walking Right
{
state = AnimationState.walkingX;
sprite.flipX = false;
}
else if ((moveDir.x < 0.0f && moveDir.y > 0.0f) || (moveDir.x < 0.0f && moveDir.y < 0.0f) || (moveDir.x < 0.0f && moveDir.y == 0.0f)) // Walking Left
{
state = AnimationState.walkingX;
sprite.flipX = true;
}
else if (lastDir.x >= 0.0f && lastDir.y == 0.0f && moveDir == Vector2.zero)
{
state = AnimationState.walkingXIdle;
}
else if (lastDir.x <= 0.0f && lastDir.y == 0.0f && moveDir == Vector2.zero)
{
state = AnimationState.walkingXIdle;
sprite.flipX = true;
}
else
{
state = AnimationState.idleDown;
}
anim.SetInteger("state", (int)state);
}
}