Бесконечный запуск анимации в Unity
У меня есть код моего врага в Unity 2d top-down, но когда я захожу в поле атаки врага, анимация его атаки просто бесконечно начинается, не успевая закончится, а должна сначала проигрываться до конца, а потом запускаться при следующей атаке, вот весь мой код:
using UnityEngine;
public class WalkerController : MonoBehaviour
{
public float chaseRadius = 5f;
public float attackRange = 1.5f;
public float moveSpeed = 2f;
public float attackDamage = 10f;
public float attackCooldown = 2f;
public Vector2 offset = Vector2.zero;
public Transform player;
public Animator anim;
private Rigidbody2D rb;
private float _nextAttackTime;
private bool _isAttacking;
private bool isMoving;
private Player _player;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
if (rb == null)
{
Debug.LogError("Rigidbody2D не найден на зомби!");
enabled = false;
return;
}
if (player != null)
{
_player = player.GetComponent<Player>();
if (_player == null)
{
Debug.LogWarning("Player script not found on the player object!");
}
}
else
{
Debug.LogWarning("Игрок не назначен в WalkerController!");
}
}
private void FixedUpdate()
{
if (player == null) return;
Vector2 offsetPosition = (Vector2)transform.position + offset;
float distanceToPlayer = Vector2.Distance(offsetPosition, player.position);
if (distanceToPlayer <= chaseRadius && !_isAttacking)
{
isMoving = true;
ChasePlayer();
if (distanceToPlayer <= attackRange)
{
_isAttacking = true;
isMoving = false;
rb.velocity = Vector2.zero;
anim.SetBool("isMoving", false);
anim.SetTrigger("Attack");
Attack(); // Начать атаку
}
}
else
{
if(_isAttacking)
{
_isAttacking = false;
anim.ResetTrigger("Attack");
}
isMoving = false;
rb.velocity = Vector2.zero;
anim.SetBool("isMoving", false);
}
anim.SetBool("isMoving", isMoving);
}
private void ChasePlayer()
{
Vector2 direction = ((Vector2)player.position - ((Vector2)transform.position + offset)).normalized;
rb.velocity = direction * moveSpeed;
anim.SetBool("isMoving", true);
}
private void Attack()
{
if (Time.time > _nextAttackTime)
{
_nextAttackTime = Time.time + attackCooldown;
if (Vector2.Distance((Vector2)transform.position + offset, player.position) <= attackRange && _player != null)
{
_player.TakeDamage(attackDamage);
Debug.Log("Зомби нанес урон игроку!");
}
_isAttacking = false;
}
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.yellow;
Vector3 offsetPosition = transform.position;
offsetPosition.x += offset.x;
offsetPosition.y += offset.y;
Gizmos.DrawWireSphere(offsetPosition, chaseRadius);
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(offsetPosition, attackRange);
}
}
Вот все мои переходы анимаций, если это важно:
idle -> angry_walk при is_moving = true angry_walk -> idle при is_moving = false any state -> attack при trigger "Attack"
Ответы (1 шт):
Автор решения: Nikolay Stuff
→ Ссылка
Проверьте настройки в аниматоре. В Transition(стрелках) должна стоять галка Has Exit Time,так же ,убедитесь ,что в самой анимации атаки убрана галка в Loop. Проверьте в дебаге , как работает логика в if (distanceToPlayer <= chaseRadius && !_isAttacking)
. Вынесите логику в методах Start()
и FixetUpdate()
в отдельные методы, для чистоты кода.