добавлены конфиги для дурнев

This commit is contained in:
MrTorex committed 2025-11-19 20:11:24 +03:00
1 parent 575e66425a
commit afdd523682
18 files changed
+377 -251

No files matched your search

@@ -78,6 +78,9 @@ namespace Code.App
containerBuilder.AddSingleton(staticDataService.UIConfig, typeof(UIConfig));
containerBuilder.AddSingleton(staticDataService.DrunkenGrandpaConfig, typeof(DrunkenGrandpaConfig));
containerBuilder.AddSingleton(staticDataService.CockroachConfig, typeof(CockroachConfig));
containerBuilder.AddSingleton(staticDataService.AudioMixerConfig, typeof(AudioMixerConfig));
containerBuilder.AddSingleton(staticDataService.SoundtrackListConfig, typeof(SoundtrackListConfig));
containerBuilder.AddSingleton(staticDataService.SFXListConfig, typeof(SFXListConfig));
@@ -0,0 +1,29 @@
using UnityEngine;
using UnityEngine.AddressableAssets;
namespace Code.Configs
{
[CreateAssetMenu(menuName = "Config/Enemies/Cockroach", fileName = "CockroachConfig")]
public class CockroachConfig : ScriptableObject
{
public AssetReference cockroachPrefab;
public int damage = 2;
public float attackCooldown = 1.5f;
public float detectionRange = 20f;
public float attackRange = 1.3f;
public float speed = 6f;
public bool isStunnable;
public float stunDuration;
public bool usesIdleMovement = true;
public float idleWanderRadius = 3f;
public float idleMoveDurationMin = 0.3f;
public float idleMoveDurationMax = 1f;
public float idlePauseDurationMin = 0.1f;
public float idlePauseDurationMax = 0.8f;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 7bc162d3127949aa950d0738beee99a4
timeCreated: 1763571220
@@ -0,0 +1,29 @@
using UnityEngine;
using UnityEngine.AddressableAssets;
namespace Code.Configs
{
[CreateAssetMenu(menuName = "Config/Enemies/DrunkenGrandpa", fileName = "DrunkenGrandpaConfig")]
public class DrunkenGrandpaConfig : ScriptableObject
{
public AssetReference drunkenGrandpaPrefab;
public int damage = 2;
public float attackCooldown = 5f;
public float detectionRange = 10f;
public float attackRange = 1.5f;
public float speed = 3f;
public bool isStunnable = true;
public float stunDuration = 3f;
public bool usesIdleMovement = true;
public float idleWanderRadius = 5f;
public float idleMoveDurationMin = 1f;
public float idleMoveDurationMax = 5f;
public float idlePauseDurationMin = 3f;
public float idlePauseDurationMax = 5f;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 4d157e8891074b90957a7434cff0ae71
timeCreated: 1763569096
@@ -11,33 +11,43 @@ namespace Code.Gameplay.Enemies
{
public abstract class BaseEnemy : MonoBehaviour
{
[Header("Base enemy configs")]
public int collisionDamage = 1;
public int attackDamage = 3;
public float detectionRange = 10f;
public float attackRange = 5f;
public float speed = 3f;
public float stunDuration = 3f;
public float attackCooldown = 1.5f;
[SerializeField] protected NavMeshAgent agent;
[SerializeField] protected Collider enemyCollider;
protected int Damage;
protected float AttackCooldown;
protected float DetectionRange;
protected float AttackRange;
protected float Speed;
protected bool IsStunnable;
protected float StunDuration;
protected bool UsesIdleMovement;
protected float IdleWanderRadius;
protected float IdleMoveDurationMin;
protected float IdleMoveDurationMax;
protected float IdlePauseDurationMin;
protected float IdlePauseDurationMax;
private bool _isStunned;
private float _currentStunTimer;
private bool _canAttack = true;
private float _attackCooldownTimer;
private enum IdleState { Moving, Paused }
private IdleState _currentIdleState = IdleState.Paused;
private float _idleTimer;
private Vector3 _idleTargetPosition;
[Inject] private IPlayerProvider _playerProvider;
protected CharacterProvider Player => _playerProvider?.Character;
protected PlayerHealth PlayerHealth => _playerProvider?.Health;
protected CustomCharacterController PlayerController => Player?.CustomCharacterController;
protected bool IsStunned;
protected float CurrentStunTimer;
protected bool CanAttack = true;
protected float AttackCooldownTimer;
protected virtual void Awake()
{
if (_playerProvider == null)
@@ -52,7 +62,7 @@ namespace Code.Gameplay.Enemies
HandleStun();
HandleAttackCooldown();
if (IsStunned) return;
if (_isStunned) return;
HandleMovement();
HandleAttack();
@@ -64,61 +74,115 @@ namespace Code.Gameplay.Enemies
var distanceToPlayer = Vector3.Distance(transform.position, Player.transform.position);
if (distanceToPlayer <= detectionRange)
if (distanceToPlayer <= DetectionRange)
{
agent.isStopped = false;
agent.SetDestination(Player.transform.position);
}
else if (UsesIdleMovement)
{
HandleIdleMovement();
}
else
{
agent.isStopped = true;
}
}
protected virtual void HandleIdleMovement()
{
_idleTimer -= Time.deltaTime;
switch (_currentIdleState)
{
case IdleState.Paused:
if (_idleTimer <= 0f)
{
// Start moving to a new random point
_currentIdleState = IdleState.Moving;
SetNewIdleDestination();
_idleTimer = Random.Range(IdleMoveDurationMin, IdleMoveDurationMax);
agent.isStopped = false;
}
break;
case IdleState.Moving:
if (_idleTimer <= 0f || HasReachedIdleDestination())
{
// Stop and pause
_currentIdleState = IdleState.Paused;
_idleTimer = Random.Range(IdlePauseDurationMin, IdlePauseDurationMax);
agent.isStopped = true;
}
break;
}
}
private void SetNewIdleDestination()
{
Vector3 randomPoint = transform.position + Random.insideUnitSphere * IdleWanderRadius;
NavMeshHit hit;
if (NavMesh.SamplePosition(randomPoint, out hit, 3f, agent.areaMask))
{
_idleTargetPosition = hit.position;
agent.SetDestination(_idleTargetPosition);
}
else
{
// Fallback: stay
_idleTargetPosition = transform.position;
}
}
private bool HasReachedIdleDestination()
{
return agent.remainingDistance <= agent.stoppingDistance;
}
protected virtual void HandleAttack() { }
protected virtual void HandleStun()
{
if (!IsStunned) return;
if (!_isStunned || !IsStunnable) return;
CurrentStunTimer -= Time.deltaTime;
_currentStunTimer -= Time.deltaTime;
if (!(CurrentStunTimer <= 0)) return;
if (!(_currentStunTimer <= 0)) return;
IsStunned = false;
_isStunned = false;
agent.isStopped = false;
enemyCollider.enabled = true;
}
protected virtual void ApplyStun()
{
IsStunned = true;
CurrentStunTimer = stunDuration;
_isStunned = true;
_currentStunTimer = StunDuration;
agent.isStopped = true;
enemyCollider.enabled = false;
}
protected virtual void HandleAttackCooldown()
{
if (!CanAttack)
if (!_canAttack)
{
AttackCooldownTimer -= Time.deltaTime;
if (AttackCooldownTimer <= 0)
_attackCooldownTimer -= Time.deltaTime;
if (_attackCooldownTimer <= 0)
{
CanAttack = true;
_canAttack = true;
}
}
}
protected virtual void DealDamage()
{
if (!CanAttack || PlayerHealth == null) return;
if (!_canAttack || PlayerHealth == null) return;
PlayerHealth.GetDamage(collisionDamage);
PlayerHealth.GetDamage(Damage);
ApplyEffectsToPlayer();
CanAttack = false;
AttackCooldownTimer = attackCooldown;
_canAttack = false;
_attackCooldownTimer = AttackCooldown;
}
protected virtual void ApplyEffectsToPlayer()
@@ -129,10 +193,10 @@ namespace Code.Gameplay.Enemies
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(transform.position, detectionRange);
Gizmos.DrawWireSphere(transform.position, DetectionRange);
Gizmos.color = new Color(0.3f, 0.3f, 0.8f, 0.4f);
Gizmos.DrawSphere(transform.position, attackRange);
Gizmos.DrawSphere(transform.position, AttackRange);
}
}
}
@@ -1,156 +1,58 @@
using Code.Configs;
using Reflex.Attributes;
using UnityEngine;
using UnityEngine.AI;
namespace Code.Gameplay.Enemies
{
public class Cockroach : BaseEnemy
{
[Header("Cockroach-Specific")]
public float wallCheckDistance = 0.5f;
public float moveForce = 10f;
public float maxSpeed = 5f;
public LayerMask climbableLayers; // ← ← ← ТОЛЬКО для стен/пола (где ползать), НЕ для игрока!
[SerializeField] private Rigidbody rb;
[SerializeField] private Transform model; // модель таракана (дочерний объект для поворота)
private Vector3 surfaceNormal = Vector3.up;
private bool isPlayerDetected = false;
private Collider[] _overlapResults = new Collider[4]; // для переиспользования
[Inject]
private void Construct(CockroachConfig cockroachConfig)
{
Damage = cockroachConfig.damage;
AttackCooldown = cockroachConfig.attackCooldown;
DetectionRange = cockroachConfig.detectionRange;
AttackRange = cockroachConfig.attackRange;
Speed = cockroachConfig.speed;
IsStunnable = cockroachConfig.isStunnable;
StunDuration = cockroachConfig.stunDuration;
UsesIdleMovement = cockroachConfig.usesIdleMovement;
IdleWanderRadius = cockroachConfig.idleWanderRadius;
IdleMoveDurationMin = cockroachConfig.idleMoveDurationMin;
IdleMoveDurationMax = cockroachConfig.idleMoveDurationMax;
IdleMoveDurationMin = cockroachConfig.idleMoveDurationMin;
IdleMoveDurationMax = cockroachConfig.idleMoveDurationMax;
IdlePauseDurationMin = cockroachConfig.idlePauseDurationMin;
IdlePauseDurationMax = cockroachConfig.idlePauseDurationMax;
}
protected override void Awake()
{
base.Awake();
// Убираем NavMeshAgent — он не нужен для лазания
if (agent != null)
{
agent.enabled = false;
Destroy(agent);
agent = null;
}
if (rb == null)
rb = GetComponent<Rigidbody>();
rb.useGravity = false;
rb.isKinematic = false;
rb.freezeRotation = true;
if (agent == null) return;
var walkableArea = NavMesh.GetAreaFromName("Cockroach");
agent.areaMask = 1 << walkableArea;
}
protected override void Update()
{
if (!Player) return;
HandleStun();
HandleAttackCooldown();
if (IsStunned) return;
DetectPlayer();
HandleMovement();
HandleAttack();
}
private void DetectPlayer()
{
// Ищем игрока по тегу через OverlapSphere — без LayerMask
int hits = Physics.OverlapSphereNonAlloc(transform.position, detectionRange, _overlapResults);
isPlayerDetected = false;
for (int i = 0; i < hits; i++)
{
if (_overlapResults[i].CompareTag("Player"))
{
isPlayerDetected = true;
break;
}
}
}
protected override void HandleMovement()
{
if (!isPlayerDetected)
{
rb.linearVelocity = Vector3.zero;
return;
}
// Направление к игроку (проекция на горизонталь, чтобы не лез вверх/вниз резко)
Vector3 toPlayer = Player.transform.position - transform.position;
toPlayer = Vector3.ProjectOnPlane(toPlayer, surfaceNormal).normalized;
// Raycast вниз и вперёд-вниз, чтобы найти поверхность
Vector3 rayOrigin = transform.position + transform.up * 0.1f;
bool foundSurface = false;
// Основной луч вниз (относительно текущей ориентации)
if (Physics.Raycast(rayOrigin, -transform.up, out RaycastHit hit, wallCheckDistance * 2, climbableLayers))
{
surfaceNormal = hit.normal;
foundSurface = true;
}
// Запасной — в мировой вниз (на случай, если "повернулся вверх ногами")
else if (Physics.Raycast(rayOrigin, -Vector3.up, out hit, wallCheckDistance * 2, climbableLayers))
{
surfaceNormal = hit.normal;
foundSurface = true;
}
// Если поверхность не найдена — не двигаемся (падаем или стоим)
if (!foundSurface)
return;
// Поворачиваем модель так, чтобы "спина" смотрела от поверхности
if (model != null)
{
// Смотрим в сторону игрока, но "встаём" на поверхность
Quaternion targetRot = Quaternion.FromToRotation(Vector3.up, surfaceNormal);
Quaternion lookRot = Quaternion.LookRotation(toPlayer, surfaceNormal);
model.rotation = Quaternion.Slerp(model.rotation, targetRot * lookRot, Time.deltaTime * 12f);
}
// Движение — в плоскости поверхности
Vector3 moveDir = Vector3.ProjectOnPlane(toPlayer, surfaceNormal).normalized;
Vector3 force = moveDir * moveForce;
rb.AddForce(force, ForceMode.Force);
rb.linearVelocity = Vector3.ClampMagnitude(rb.linearVelocity, maxSpeed);
}
protected override void HandleAttack()
{
if (!Player || !isPlayerDetected) return;
if (!Player) return;
var distance = Vector3.Distance(transform.position, Player.transform.position);
float distance = Vector3.Distance(transform.position, Player.transform.position);
if (distance <= attackRange && CanAttack)
{
if (!(distance <= AttackRange)) return;
if (Player.CustomCharacterController.IsSliding)
ApplyStun();
else
DealDamage();
}
}
// Столкновение = -1 HP (по ТЗ)
private void OnCollisionEnter(Collision col)
{
if (col.gameObject.CompareTag("Player"))
{
PlayerHealth?.GetDamage(collisionDamage);
ApplyEffectsToPlayer();
}
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(transform.position, detectionRange);
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, attackRange);
// Покажем направление поверхности в эдиторе (если запущено)
if (Application.isPlaying)
{
Gizmos.color = Color.cyan;
Gizmos.DrawLine(transform.position, transform.position + surfaceNormal * 0.4f);
}
}
}
}
@@ -1,3 +1,5 @@
using Code.Configs;
using Reflex.Attributes;
using UnityEngine;
using UnityEngine.AI;
@@ -5,6 +7,30 @@ namespace Code.Gameplay.Enemies
{
public class DrunkenGrandpa : BaseEnemy
{
[Inject]
private void Construct(DrunkenGrandpaConfig drunkenGrandpaConfig)
{
Damage = drunkenGrandpaConfig.damage;
AttackCooldown = drunkenGrandpaConfig.attackCooldown;
DetectionRange = drunkenGrandpaConfig.detectionRange;
AttackRange = drunkenGrandpaConfig.attackRange;
Speed = drunkenGrandpaConfig.speed;
IsStunnable = drunkenGrandpaConfig.isStunnable;
StunDuration = drunkenGrandpaConfig.stunDuration;
UsesIdleMovement = drunkenGrandpaConfig.usesIdleMovement;
IdleWanderRadius = drunkenGrandpaConfig.idleWanderRadius;
IdleMoveDurationMin = drunkenGrandpaConfig.idleMoveDurationMin;
IdleMoveDurationMax = drunkenGrandpaConfig.idleMoveDurationMax;
IdleMoveDurationMin = drunkenGrandpaConfig.idleMoveDurationMin;
IdleMoveDurationMax = drunkenGrandpaConfig.idleMoveDurationMax;
IdlePauseDurationMin = drunkenGrandpaConfig.idlePauseDurationMin;
IdlePauseDurationMax = drunkenGrandpaConfig.idlePauseDurationMax;
}
protected override void Awake()
{
base.Awake();
@@ -21,7 +47,7 @@ namespace Code.Gameplay.Enemies
var distance = Vector3.Distance(transform.position, Player.transform.position);
if (!(distance <= attackRange)) return;
if (!(distance <= AttackRange)) return;
if (Player.CustomCharacterController.IsSliding)
ApplyStun();
@@ -18,7 +18,7 @@ namespace Code.Gameplay.Enemies
if (!Player) return;
var direction = (Player.transform.position - transform.position).normalized;
transform.position += direction * (speed * Time.deltaTime);
transform.position += direction * (Speed * Time.deltaTime);
}
protected override void HandleAttack()
@@ -27,7 +27,7 @@ namespace Code.Gameplay.Enemies
var distance = Vector3.Distance(transform.position, Player.transform.position);
if (!(distance < attackRange)) return;
if (!(distance < AttackRange)) return;
PlayerHealth.GetDamage(PlayerHealth.MaxHealthPoints);
base.ApplyEffectsToPlayer();
@@ -36,7 +36,7 @@ namespace Code.Gameplay.Enemies
private void OnDrawGizmosSelected()
{
Gizmos.color = new Color(0.3f, 0.3f, 0.8f, 0.4f);
Gizmos.DrawSphere(transform.position, attackRange);
Gizmos.DrawSphere(transform.position, AttackRange);
}
}
}
@@ -21,6 +21,8 @@ namespace Code.StaticData
SFXListConfig SFXListConfig { get; }
DispatcherSoundListConfig DispatcherSoundListConfig { get; }
EnemiesSoundListConfig EnemiesSoundListConfig { get; }
DrunkenGrandpaConfig DrunkenGrandpaConfig { get; }
CockroachConfig CockroachConfig { get; }
void Load();
Task<T> InstantiateAsset<T>(AssetReference assetReference) where T : Behaviour;
}
@@ -20,6 +20,8 @@ namespace Code.StaticData
public SFXListConfig SFXListConfig { get; private set; }
public DispatcherSoundListConfig DispatcherSoundListConfig { get; private set; }
public EnemiesSoundListConfig EnemiesSoundListConfig { get; private set; }
public DrunkenGrandpaConfig DrunkenGrandpaConfig {get; private set;}
public CockroachConfig CockroachConfig { get; private set; }
public void Load()
{
@@ -31,6 +33,7 @@ namespace Code.StaticData
PlayerConfig = Resources.Load<PlayerConfig>(string.Format(StringPaths.ConfigSingle, "App", "PlayerConfig"));
LoadAudioConfigs();
LoadEnemiesConfigs();
}
private void LoadAudioConfigs()
@@ -42,6 +45,12 @@ namespace Code.StaticData
EnemiesSoundListConfig = Resources.Load<EnemiesSoundListConfig>(string.Format(StringPaths.ConfigSingle, "Audio", "EnemiesSoundListConfig"));
}
private void LoadEnemiesConfigs()
{
DrunkenGrandpaConfig = Resources.Load<DrunkenGrandpaConfig>(string.Format(StringPaths.ConfigSingle, "Enemies", "DrunkenGrandpaConfig"));
CockroachConfig = Resources.Load<CockroachConfig>(string.Format(StringPaths.ConfigSingle, "Enemies", "CockroachConfig"));
}
public async Task<T> InstantiateAsset<T>(AssetReference assetReference) where T : Behaviour
{
return (await Addressables.InstantiateAsync(assetReference).ToUniTask()).GetComponent<T>();