I wrote the code in Unity hoping that the character can move in all directions in two dimensions if I press the direction key. (If I press the shift key, it moves fast.) However, after writing the code related to the animation, the character gets a bug that doesn't move even if I press the direction key. I hope you can tell me a solution or a solution for someone with a similar problem.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerManager : MonoBehaviour
{
public float speed;
protected Vector3 vector;
public float runSpeed;
private float applyRunSpeed;
private Animator anim;
private void Start()
{
anim = GetComponent<Animator>();
}
IEnumerator MoveCoroutine()
{
while (Input.GetAxisRaw("Horizontal") != 0 || Input.GetAxisRaw("Vertical") != 0)
{
if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
{
applyRunSpeed = runSpeed;
}
else
{
applyRunSpeed = 0;
}
vector.Set(Input.GetAxisRaw("Horizontal"),
Input.GetAxisRaw("Vertical"), transform.position.z);
anim.SetFloat("DirX", vector.x);
anim.SetFloat("DirY", vector.y);
anim.SetBool("Idle", false);
if (vector.x != 0 || vector.y != 0)
{
transform.Translate(vector.x * (speed + applyRunSpeed) * Time.deltaTime,
vector.y * (speed + applyRunSpeed) * Time.deltaTime, 0);
}
yield return null;
}
anim.SetBool("Idle", true);
}
private void Update()
{
if (Input.GetAxisRaw("Horizontal") != 0 || Input.GetAxisRaw("Vertical") != 0)
{
StartCoroutine(MoveCoroutine());
}
}
}
I've heard from chat GPT that this code does a lot of running unnecessarily because of the Corutine, and I've heard back that there's no code that actually moves the Sprite. But it worked well until I wrote the code related to animation (SetFloat, SetBool), so I suspect there's been a problem in the animation-related part.
Or it seems that the computer couldn't handle it because the amount of computation was high in the corutine-related part. I am not satisfied with any of them.