/
darov
/
Platformer
Обзор
Документация
Войти
/
darov
/
Platformer
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Assets/Scripts/EnemyController.cs
100 строк
3 KB
Roman Danilov
comment
15 окт 2025, 07:53
15 окт 2025, 07:53
80f1cc3
Код
Авторство
О чём код?
using System.Collections; using UnityEngine; public class EnemyController : MonoBehaviour, IMovingDetector { private const int IdleState = 0; private const int WalkState = 1; private const int RevertState = 2; private const int JumpState = 3; private const int FallState = 4; [SerializeField] private float _moveSpeed; [SerializeField] private float _timeToRevert; [SerializeField] private bool _isStand; [Header("Jumper settings")] [SerializeField] private bool _isJumper; [SerializeField] private float _timeForTakeoff, _timeForRest; private Rigidbody2D _rigidbody; private IGroundCheck _ground; private int _currentState; public bool IsMoving { get { return _currentState == WalkState || _currentState == JumpState; } } public float Direction { get { return _moveSpeed; } } private void Start() { _rigidbody = GetComponentInParent<Rigidbody2D>(); _ground = GetComponentInParent<IGroundCheck>(); if (_isStand) { _currentState = IdleState; } else if (_isJumper) { _currentState = JumpState; StartCoroutine(WaitAndChangeState(_timeForTakeoff, FallState)); } else { _currentState = WalkState; } } private void Update() { switch (_currentState) { case IdleState: //�������� ����������� �� OnTriggerEnter ��� FallState, //����� RevertState ��� JumpState break; case WalkState: _rigidbody.velocity = new(_moveSpeed, _rigidbody.velocity.y); break; case RevertState: _moveSpeed *= -1; _currentState = _isJumper ? JumpState : WalkState; if (_isJumper) StartCoroutine(WaitAndChangeState(_timeForTakeoff, FallState)); break; case JumpState: _rigidbody.velocity = Vector2.right * _moveSpeed + Vector2.up * Mathf.Abs(_moveSpeed); //�������� ����������� �� RevertState, ����� FallState break; case FallState: if (_ground.IsGrounded) { _currentState = IdleState; StartCoroutine(WaitAndChangeState(_timeForRest, JumpState)); StartCoroutine(WaitAndChangeState(_timeForRest + _timeForTakeoff, FallState)); } break; } } private void OnTriggerEnter2D(Collider2D collision) { if (collision.TryGetComponent<IStopper>(out _)) { _currentState = IdleState; StopAllCoroutines(); StartCoroutine(WaitAndChangeState(_timeToRevert, RevertState)); } } private IEnumerator WaitAndChangeState(float time, int state) { yield return new WaitForSeconds(time); _currentState = state; } }