Есть классы, есть двери, есть механика вселения, свага есть

This commit is contained in:
vladislove committed 2026-10-21 21:21:16 +03:00
1 parent 2ae795c30a
commit 0f9a539460
69 files changed
+3960 -299

No files matched your search

@@ -0,0 +1,207 @@
using UnityEngine;
namespace _Project.Scripts.PlayerUtils
{
public enum BodyClass
{
Spirit,
Scout,
Trooper,
Juggernaut,
Sniper
}
[CreateAssetMenu(menuName = "Player/Body Profile", fileName = "BodyProfile")]
public class BodyProfile : ScriptableObject
{
public BodyClass bodyClass = BodyClass.Trooper;
public string displayName = "Штурмовик";
public float maxHealth = 100f;
[Header("Передвижение (PlayerMovement)")]
public float moveSpeed = 6.5f;
public float sprintSpeed = 9.5f;
public float crouchSpeed = 3f;
public bool canSlide = true;
public float slideInitialSpeed = 15f;
public float slideDuration = 0.85f;
public float airAcceleration = 80f;
public float jumpHeight = 1.35f;
public float gravity = -25f;
public float standingHeight = 2f;
[Header("Камера и Звук (PlayerCamera & Sound)")]
public float standingCameraY = 1.6f;
public float crouchingCameraY = 0.8f;
public float walkBobSpeed = 12f;
public float walkBobAmount = 0.04f;
public float slideTiltAngle = 4f;
public float footstepPitch = 1f;
[Header("Оружие и Снаряды (PlayerCombat)")]
public bool canShoot = true;
public bool isAutomatic = true;
public float damage = 25f;
public float fireRate = 0.12f;
public float weaponRange = 100f;
public int pelletsPerShot = 1;
public float spreadAngle = 0f;
public bool pierceTargets = false;
public float recoilKick = 1.2f;
[Header("Параметры летящего снаряда")]
[Tooltip("Скорость полёта снаряда в м/с (чтобы от него можно было увернуться!)")]
public float projectileSpeed = 30f;
public float projectileSize = 0.22f;
public Color projectileColor = new Color(1f, 0.6f, 0.1f, 1f);
public static BodyProfile CreateDefault(BodyClass type)
{
var p = CreateInstance<BodyProfile>();
p.bodyClass = type;
switch (type)
{
case BodyClass.Spirit:
p.displayName = "ДУХ МЩЕНИЯ";
p.maxHealth = 25f;
p.moveSpeed = 11f;
p.sprintSpeed = 15f;
p.crouchSpeed = 6f;
p.canSlide = true;
p.slideInitialSpeed = 22f;
p.slideDuration = 1.1f;
p.airAcceleration = 160f;
p.jumpHeight = 1.8f;
p.gravity = -18f;
p.standingHeight = 1.6f;
p.standingCameraY = 1.3f;
p.walkBobAmount = 0.015f;
p.canShoot = false;
break;
case BodyClass.Scout:
p.displayName = "СКАУТ (Чистильщик)";
p.maxHealth = 70f;
p.moveSpeed = 9f;
p.sprintSpeed = 13f;
p.crouchSpeed = 4.5f;
p.canSlide = true;
p.slideInitialSpeed = 20f;
p.slideDuration = 1.15f;
p.airAcceleration = 140f;
p.jumpHeight = 1.65f;
p.gravity = -24f;
p.standingHeight = 1.8f;
p.standingCameraY = 1.5f;
p.walkBobSpeed = 15f;
p.walkBobAmount = 0.05f;
p.slideTiltAngle = 7f;
p.footstepPitch = 1.2f;
p.canShoot = true;
p.isAutomatic = true;
p.damage = 14f;
p.fireRate = 0.08f;
p.weaponRange = 45f;
p.pelletsPerShot = 1;
p.spreadAngle = 2.5f;
p.recoilKick = 0.6f;
p.projectileSpeed = 36f; // Жёлтые быстрые очереди
p.projectileSize = 0.16f;
p.projectileColor = new Color(1f, 0.9f, 0.2f, 1f);
break;
case BodyClass.Trooper:
p.displayName = "ШТУРМОВИК СБ";
p.maxHealth = 120f;
p.moveSpeed = 6.5f;
p.sprintSpeed = 9.5f;
p.crouchSpeed = 3f;
p.canSlide = true;
p.slideInitialSpeed = 15f;
p.slideDuration = 0.85f;
p.airAcceleration = 80f;
p.jumpHeight = 1.35f;
p.gravity = -25f;
p.standingHeight = 2f;
p.standingCameraY = 1.6f;
p.walkBobSpeed = 12f;
p.walkBobAmount = 0.04f;
p.footstepPitch = 1f;
p.canShoot = true;
p.isAutomatic = true;
p.damage = 25f;
p.fireRate = 0.14f;
p.weaponRange = 90f;
p.pelletsPerShot = 1;
p.spreadAngle = 1.2f;
p.recoilKick = 1.1f;
p.projectileSpeed = 28f; // Голубые плазменные сгустки средней скорости
p.projectileSize = 0.22f;
p.projectileColor = new Color(0.2f, 0.7f, 1f, 1f);
break;
case BodyClass.Juggernaut:
p.displayName = "ДЖАГГЕРНАУТ (Танк)";
p.maxHealth = 280f;
p.moveSpeed = 4.2f;
p.sprintSpeed = 5.8f;
p.crouchSpeed = 2f;
p.canSlide = false;
p.airAcceleration = 35f;
p.jumpHeight = 0.85f;
p.gravity = -35f;
p.standingHeight = 2.4f;
p.standingCameraY = 1.95f;
p.crouchingCameraY = 1.2f;
p.walkBobSpeed = 7f;
p.walkBobAmount = 0.07f;
p.footstepPitch = 0.65f;
p.canShoot = true;
p.isAutomatic = false;
p.damage = 18f;
p.fireRate = 0.85f;
p.weaponRange = 35f;
p.pelletsPerShot = 8;
p.spreadAngle = 7f;
p.recoilKick = 4.2f;
p.projectileSpeed = 22f; // Крупная ярко-оранжевая картечь (отлично видно для уворота!)
p.projectileSize = 0.25f;
p.projectileColor = new Color(1f, 0.3f, 0.1f, 1f);
break;
case BodyClass.Sniper:
p.displayName = "СНАЙПЕР-ФАНТОМ";
p.maxHealth = 85f;
p.moveSpeed = 6.2f;
p.sprintSpeed = 8.8f;
p.crouchSpeed = 3.2f;
p.canSlide = true;
p.slideInitialSpeed = 14f;
p.slideDuration = 0.8f;
p.airAcceleration = 90f;
p.jumpHeight = 1.45f;
p.gravity = -20f;
p.standingHeight = 2f;
p.standingCameraY = 1.65f;
p.walkBobSpeed = 10f;
p.walkBobAmount = 0.015f;
p.footstepPitch = 1.05f;
p.canShoot = true;
p.isAutomatic = false;
p.damage = 110f;
p.fireRate = 1.1f;
p.weaponRange = 200f;
p.pelletsPerShot = 1;
p.spreadAngle = 0f;
p.pierceTargets = true;
p.recoilKick = 3.0f;
p.projectileSpeed = 60f; // Фиолетовый скоростной заряд рейлгана
p.projectileSize = 0.28f;
p.projectileColor = new Color(0.85f, 0.2f, 1f, 1f);
break;
}
return p;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 8addb03ef12f4e9eb6834129b77b5969
timeCreated: 1792605123
@@ -1,5 +1,4 @@
using UnityEngine;
using UnityEngine.InputSystem;
namespace _Project.Scripts.PlayerUtils
{
@@ -24,6 +23,8 @@ namespace _Project.Scripts.PlayerUtils
[SerializeField] private float sprintBobAmount = 0.07f;
[SerializeField] private float impactRecoverySpeed = 6f;
public Transform CameraTransform => cameraPosition;
private PlayerControls controls;
private PlayerMovement movement;
@@ -47,6 +48,23 @@ namespace _Project.Scripts.PlayerUtils
yRotation = transform.eulerAngles.y;
}
public void ApplyProfile(BodyProfile profile)
{
standingCameraY = profile.standingCameraY;
crouchingCameraY = profile.crouchingCameraY;
walkBobSpeed = profile.walkBobSpeed;
sprintBobSpeed = profile.walkBobSpeed * 1.25f;
walkBobAmount = profile.walkBobAmount;
sprintBobAmount = profile.walkBobAmount * 1.6f;
slideCameraTiltAngle = profile.slideTiltAngle;
}
public void SetYaw(float yaw)
{
yRotation = yaw;
transform.rotation = Quaternion.Euler(0f, yRotation, 0f);
}
private void Update()
{
HandleMouseLook();
@@ -56,12 +74,13 @@ namespace _Project.Scripts.PlayerUtils
private void HandleMouseLook()
{
Vector2 lookInput = controls.Player.Look.ReadValue<Vector2>();
float dt = Time.unscaledDeltaTime;
cameraPitch -= lookInput.y * mouseSensitivity;
cameraPitch = Mathf.Clamp(cameraPitch, -maxLookAngle, maxLookAngle);
float targetTilt = movement.IsSliding ? -slideCameraTiltAngle : 0f;
currentCameraTilt = Mathf.Lerp(currentCameraTilt, targetTilt, Time.deltaTime * 10f);
currentCameraTilt = Mathf.Lerp(currentCameraTilt, targetTilt, dt * 10f);
cameraPosition.localRotation = Quaternion.Euler(cameraPitch, 0f, currentCameraTilt);
@@ -71,9 +90,10 @@ namespace _Project.Scripts.PlayerUtils
private void HandleCameraAndBobbing()
{
float dt = Time.unscaledDeltaTime;
bool isLowered = movement.IsCrouching || movement.IsSliding;
float targetCamY = isLowered ? crouchingCameraY : standingCameraY;
baseCameraY = Mathf.Lerp(baseCameraY, targetCamY, Time.deltaTime * crouchTransitionSpeed);
baseCameraY = Mathf.Lerp(baseCameraY, targetCamY, dt * crouchTransitionSpeed);
bool isMoving = movement.MoveInput.sqrMagnitude > 0.01f && movement.IsGrounded && !movement.IsSliding;
@@ -82,13 +102,12 @@ namespace _Project.Scripts.PlayerUtils
float speed = movement.IsSprinting ? sprintBobSpeed : walkBobSpeed;
float amount = movement.IsSprinting ? sprintBobAmount : walkBobAmount;
bobTimer += Time.deltaTime * speed;
bobTimer += dt * speed;
bobOffset.x = Mathf.Cos(bobTimer * 0.5f) * amount;
bobOffset.y = Mathf.Sin(bobTimer) * amount;
if (Mathf.Sin(bobTimer) <= -0.9f && !stepTaken)
{
// ВЫЗОВ ЗВУКА ИЗ НОВОГО МОДУЛЯ
Player.Instance.Sound.PlayFootstep(movement.IsSprinting);
stepTaken = true;
}
@@ -98,10 +117,10 @@ namespace _Project.Scripts.PlayerUtils
{
bobTimer = 0f;
stepTaken = false;
bobOffset = Vector3.Lerp(bobOffset, Vector3.zero, Time.deltaTime * 10f);
bobOffset = Vector3.Lerp(bobOffset, Vector3.zero, dt * 10f);
}
currentImpactOffset = Mathf.Lerp(currentImpactOffset, 0f, Time.deltaTime * impactRecoverySpeed);
currentImpactOffset = Mathf.Lerp(currentImpactOffset, 0f, dt * impactRecoverySpeed);
cameraPosition.localPosition = new Vector3(bobOffset.x, baseCameraY + bobOffset.y - currentImpactOffset, 0f);
}
@@ -5,13 +5,9 @@ namespace _Project.Scripts.PlayerUtils
{
public class PlayerCombat : MonoBehaviour
{
[Header("Оружие и Стрельба (Hitscan)")]
[SerializeField] private float damage = 25f;
[SerializeField] private float fireRate = 0.12f;
[SerializeField] private float weaponRange = 100f;
[Header("Оружие и Стрельба (Projectiles)")]
[SerializeField] private bool canShoot = true;
[SerializeField] private LayerMask hitLayers = ~0;
[SerializeField] private bool isAutomatic = true;
[SerializeField] private float recoilKick = 1.2f;
[Header("Эффекты (без звука)")]
[SerializeField] private ParticleSystem muzzleFlash;
@@ -21,6 +17,7 @@ namespace _Project.Scripts.PlayerUtils
[SerializeField] private Transform cameraPosition;
private PlayerControls controls;
private BodyProfile currentProfile;
private float shootTimer = 0f;
private bool isShootingInput = false;
@@ -32,45 +29,51 @@ namespace _Project.Scripts.PlayerUtils
controls.Player.Attack.canceled += _ => isShootingInput = false;
}
public void ApplyProfile(BodyProfile profile)
{
currentProfile = profile;
canShoot = profile.canShoot;
shootTimer = 0f;
}
private void Update()
{
if (shootTimer > 0f) shootTimer -= Time.deltaTime;
if (shootTimer > 0f) shootTimer -= Time.unscaledDeltaTime;
if (!canShoot || currentProfile == null) return;
bool shootPressed = isShootingInput || (Mouse.current != null && (isAutomatic ? Mouse.current.leftButton.isPressed : Mouse.current.leftButton.wasPressedThisFrame));
bool isAuto = currentProfile.isAutomatic;
bool shootPressed = isShootingInput || (Mouse.current != null && (isAuto ? Mouse.current.leftButton.isPressed : Mouse.current.leftButton.wasPressedThisFrame));
if (shootPressed && shootTimer <= 0f)
{
Shoot();
if (!isAuto) isShootingInput = false;
}
}
private void Shoot()
{
shootTimer = fireRate;
shootTimer = currentProfile.fireRate;
// ВЫЗОВ ЗВУКА ИЗ НОВОГО МОДУЛЯ
Player.Instance.Sound.PlayShoot();
if (muzzleFlash != null) muzzleFlash.Play();
Player.Instance.CameraController.ApplyRecoil(recoilKick);
Player.Instance.CameraController.ApplyRecoil(currentProfile.recoilKick);
Ray ray = new Ray(cameraPosition.position, cameraPosition.forward);
if (Physics.Raycast(ray, out RaycastHit hit, weaponRange, hitLayers, QueryTriggerInteraction.Ignore))
int pellets = Mathf.Max(1, currentProfile.pelletsPerShot);
float spread = currentProfile.spreadAngle;
Vector3 spawnPos = cameraPosition.position + cameraPosition.forward * 0.6f - cameraPosition.up * 0.1f;
for (int i = 0; i < pellets; i++)
{
if (hit.collider.TryGetComponent<IDamageable>(out var damageable))
Vector3 dir = cameraPosition.forward;
if (spread > 0.01f)
{
damageable.TakeDamage(damage);
}
else if (hit.rigidbody != null)
{
hit.rigidbody.AddForceAtPosition(-hit.normal * (damage * 10f), hit.point, ForceMode.Impulse);
dir = Quaternion.Euler(
Random.Range(-spread, spread),
Random.Range(-spread, spread), 0f) * dir;
}
if (impactPrefab != null)
{
GameObject impact = Instantiate(impactPrefab, hit.point + (hit.normal * 0.001f), Quaternion.LookRotation(hit.normal));
Destroy(impact, 3f);
}
Projectile.Spawn(spawnPos, dir, currentProfile, true, gameObject, hitLayers, impactPrefab);
}
}
}
@@ -12,6 +12,7 @@ namespace _Project.Scripts.PlayerUtils
[SerializeField] private float crouchSpeed = 3f;
[Header("Параметры Подката (Slide)")]
[SerializeField] private bool canSlide = true;
[SerializeField] private float slideInitialSpeed = 15f;
[SerializeField] private float slideDuration = 0.85f;
[SerializeField] private float slideFriction = 2.8f;
@@ -22,7 +23,6 @@ namespace _Project.Scripts.PlayerUtils
[SerializeField] private float groundAcceleration = 10f;
[SerializeField] private float airAcceleration = 80f;
[SerializeField] private float airCap = 2.0f;
[SerializeField] private bool showSpeedometer = true;
[Header("Гравитация и Прыжок")]
[SerializeField] private float jumpHeight = 1.35f;
@@ -47,6 +47,7 @@ namespace _Project.Scripts.PlayerUtils
public bool IsSliding { get; private set; }
public Vector2 MoveInput { get; private set; }
public float CurrentSpeed => horizontalVelocity.magnitude;
private bool wasGrounded;
private float jumpBufferTimer = 0f;
private Vector3 horizontalVelocity = Vector3.zero;
@@ -57,15 +58,16 @@ namespace _Project.Scripts.PlayerUtils
private Vector3 slideDirection = Vector3.zero;
private float slideCooldownTimer = 0f;
private void Start()
private void Awake()
{
rb = GetComponent<Rigidbody>();
col = GetComponent<CapsuleCollider>();
rb.useGravity = false;
rb.freezeRotation = true;
rb.interpolation = RigidbodyInterpolation.None;
}
private void Start()
{
controls = Player.Instance.Controls;
controls.Player.Sprint.started += _ => IsSprinting = true;
@@ -77,12 +79,35 @@ namespace _Project.Scripts.PlayerUtils
controls.Player.Jump.performed += _ => QueueJump();
}
public void ApplyProfile(BodyProfile profile)
{
moveSpeed = profile.moveSpeed;
sprintSpeed = profile.sprintSpeed;
crouchSpeed = profile.crouchSpeed;
canSlide = profile.canSlide;
slideInitialSpeed = profile.slideInitialSpeed;
slideDuration = profile.slideDuration;
airAcceleration = profile.airAcceleration;
jumpHeight = profile.jumpHeight;
gravity = profile.gravity;
standingHeight = profile.standingHeight;
if (!canSlide && IsSliding) StopSlide();
}
public void AddVerticalImpulse(float velocityY)
{
verticalVelocity = velocityY;
IsGrounded = false;
}
private void Update()
{
MoveInput = controls.Player.Move.ReadValue<Vector2>();
if (jumpBufferTimer > 0f) jumpBufferTimer -= Time.deltaTime;
if (slideCooldownTimer > 0f) slideCooldownTimer -= Time.deltaTime;
float dt = Time.unscaledDeltaTime;
if (jumpBufferTimer > 0f) jumpBufferTimer -= dt;
if (slideCooldownTimer > 0f) slideCooldownTimer -= dt;
if (Mouse.current != null && Mathf.Abs(Mouse.current.scroll.y.ReadValue()) > 0.1f)
QueueJump();
@@ -100,7 +125,11 @@ namespace _Project.Scripts.PlayerUtils
ApplyMovement();
rb.linearVelocity = new Vector3(horizontalVelocity.x, verticalVelocity, horizontalVelocity.z);
float timeMult = Player.Instance.Possession != null ? Player.Instance.Possession.PlayerTimeMultiplier : 1f;
rb.linearVelocity = new Vector3(
horizontalVelocity.x * timeMult,
verticalVelocity,
horizontalVelocity.z * timeMult);
wasGrounded = IsGrounded;
}
@@ -108,7 +137,7 @@ namespace _Project.Scripts.PlayerUtils
{
bool isLowered = IsCrouching || IsSliding;
float targetHeight = isLowered ? crouchingHeight : standingHeight;
col.height = Mathf.Lerp(col.height, targetHeight, Time.deltaTime * crouchTransitionSpeed);
col.height = Mathf.Lerp(col.height, targetHeight, Time.unscaledDeltaTime * crouchTransitionSpeed);
col.center = new Vector3(col.center.x, col.height * 0.5f, col.center.z);
}
@@ -126,8 +155,6 @@ namespace _Project.Scripts.PlayerUtils
jumpBufferTimer = 0f;
Player.Instance.CameraController.TriggerJumpImpact();
// ВЫЗОВ ЗВУКА ИЗ НОВОГО МОДУЛЯ
Player.Instance.Sound.PlayJump();
}
@@ -201,7 +228,6 @@ namespace _Project.Scripts.PlayerUtils
if (!wasGrounded && IsGrounded)
{
// ВЫЗОВ ЗВУКА ИЗ НОВОГО МОДУЛЯ
Player.Instance.Sound.PlayLand();
}
@@ -217,7 +243,7 @@ namespace _Project.Scripts.PlayerUtils
private void OnCrouchPressed()
{
if (IsSprinting && IsGrounded && MoveInput.y > 0.2f && slideCooldownTimer <= 0f) StartSlide();
if (canSlide && IsSprinting && IsGrounded && MoveInput.y > 0.2f && slideCooldownTimer <= 0f) StartSlide();
else IsCrouching = true;
}
@@ -235,7 +261,6 @@ namespace _Project.Scripts.PlayerUtils
slideDirection = (transform.forward * MoveInput.y + transform.right * MoveInput.x).normalized;
if (slideDirection.sqrMagnitude < 0.01f) slideDirection = transform.forward;
// ВЫЗОВ ЗВУКА ИЗ НОВОГО МОДУЛЯ
Player.Instance.Sound.PlaySlide();
}
@@ -244,6 +269,5 @@ namespace _Project.Scripts.PlayerUtils
IsSliding = false;
slideCooldownTimer = slideCooldown;
}
}
}
@@ -0,0 +1,255 @@
using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem;
namespace _Project.Scripts.PlayerUtils
{
public class PlayerPossession : MonoBehaviour, IDamageable
{
[Header("Профиль Духа (Форма по умолчанию)")]
[SerializeField] private BodyProfile spiritProfile;
[Header("Настройки Вселения (Possession)")]
[Tooltip("Радиус зоны вселения в метрах")]
[SerializeField] private float possessRange = 12f;
[Tooltip("С какого максимального расстояния прицел замечает врага и показывает сферу зоны")]
[SerializeField] private float maxAimLookDistance = 60f;
[SerializeField] private float possessDashDuration = 0.15f;
[SerializeField] private LayerMask possessRayMask = ~0;
[Header("Визуал Сферы Зоны Вселения")]
[Tooltip("Если true — сфера рисуется вокруг врага (показывая зону, куда надо войти). Если false — вокруг игрока.")]
[SerializeField] private bool centerSphereOnTarget = true;
[SerializeField] private Color zoneReadyColor = new Color(0.1f, 0.95f, 1f, 0.10f); // Враг в зоне (можно жать E)
[SerializeField] private Color zoneOutOfRangeColor = new Color(1f, 0.35f, 0.35f, 0.06f); // Навёлся, но далеко
[Header("Замедление времени в форме Духа")]
[SerializeField, Range(0.1f, 1f)] private float spiritTimeScale = 0.45f;
public BodyProfile CurrentProfile { get; private set; }
public bool IsInSpiritForm => CurrentProfile != null && CurrentProfile.bodyClass == BodyClass.Spirit;
public float CurrentHealth { get; private set; }
public float MaxHealth => CurrentProfile != null ? CurrentProfile.maxHealth : 25f;
// Враг, на которого наведён прицел (на любом расстоянии до maxAimLookDistance)
public EnemyAI AimedEnemy { get; private set; }
// Находится ли этот враг внутри сферы вселения (possessRange)
public bool IsTargetInPossessZone { get; private set; }
public float PlayerTimeMultiplier =>
IsInSpiritForm ? (1f / Mathf.Max(0.1f, Time.timeScale)) * 0.85f : 1f;
private Transform _camTransform;
private bool _isTransitioning;
private float _invulnerableTimer;
// Полупрозрачная сфера зоны вселения
private GameObject _zoneSphere;
private Renderer _zoneRenderer;
private Material _zoneMaterial;
private float _currentZoneAlpha;
private void Awake()
{
if (spiritProfile == null)
spiritProfile = BodyProfile.CreateDefault(BodyClass.Spirit);
CreatePossessionZoneSphere();
}
private void Start()
{
_camTransform = Player.Instance.CameraController.CameraTransform;
EnterSpiritForm(false);
}
private void CreatePossessionZoneSphere()
{
_zoneSphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
_zoneSphere.name = "PossessionZoneSphere";
// Убираем коллайдер, это чисто визуальная голограмма зоны
var col = _zoneSphere.GetComponent<Collider>();
if (col != null) Destroy(col);
_zoneRenderer = _zoneSphere.GetComponent<Renderer>();
_zoneRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
_zoneRenderer.receiveShadows = false;
// Используем прозрачный шейдер, который рисуется поверх и мягко подсвечивает площадь
Shader shader = Shader.Find("Sprites/Default");
_zoneMaterial = new Material(shader);
_zoneMaterial.color = Color.clear;
_zoneRenderer.material = _zoneMaterial;
_zoneSphere.SetActive(false);
}
private void Update()
{
if (_invulnerableTimer > 0f) _invulnerableTimer -= Time.unscaledDeltaTime;
if (_isTransitioning)
{
if (_zoneSphere != null) _zoneSphere.SetActive(false);
return;
}
UpdateAimedTarget();
UpdateZoneVisual();
HandleInput();
}
private void UpdateAimedTarget()
{
AimedEnemy = null;
IsTargetInPossessZone = false;
if (_camTransform == null) return;
Ray ray = new Ray(_camTransform.position, _camTransform.forward);
if (Physics.SphereCast(ray, 0.5f, out RaycastHit hit, maxAimLookDistance, possessRayMask, QueryTriggerInteraction.Ignore))
{
var enemy = hit.collider.GetComponentInParent<EnemyAI>();
if (enemy != null && enemy.CanBePossessed)
{
AimedEnemy = enemy;
float dist = Vector3.Distance(transform.position, enemy.transform.position);
IsTargetInPossessZone = dist <= possessRange;
}
}
}
private void UpdateZoneVisual()
{
if (_zoneSphere == null) return;
if (AimedEnemy != null)
{
if (!_zoneSphere.activeSelf) _zoneSphere.SetActive(true);
// Диаметр сферы = 2 * радиус (possessRange)
float diameter = possessRange * 2f;
_zoneSphere.transform.localScale = new Vector3(diameter, diameter, diameter);
// Центр сферы: либо на враге, либо на игроке
Vector3 center = centerSphereOnTarget ? AimedEnemy.transform.position : transform.position;
_zoneSphere.transform.position = center;
Color targetColor = IsTargetInPossessZone ? zoneReadyColor : zoneOutOfRangeColor;
_zoneMaterial.color = Color.Lerp(_zoneMaterial.color, targetColor, Time.unscaledDeltaTime * 12f);
}
else
{
if (_zoneSphere.activeSelf)
{
_zoneMaterial.color = Color.clear;
_zoneSphere.SetActive(false);
}
}
}
private void HandleInput()
{
if (Keyboard.current == null) return;
// Клавиша E — Вселиться, если враг под прицелом И находится внутри сферы!
if (Keyboard.current.eKey.wasPressedThisFrame && AimedEnemy != null && IsTargetInPossessZone)
{
StartCoroutine(PossessRoutine(AimedEnemy));
}
// Клавиша Q — Покинуть тело
else if (Keyboard.current.qKey.wasPressedThisFrame && !IsInSpiritForm)
{
EnterSpiritForm(true);
}
}
private IEnumerator PossessRoutine(EnemyAI target)
{
_isTransitioning = true;
if (_zoneSphere != null) _zoneSphere.SetActive(false);
BodyProfile newProfile = target.profile != null
? target.profile
: BodyProfile.CreateDefault(target.enemyClass);
float inheritedHealth = Mathf.Max(target.CurrentHealth, newProfile.maxHealth * 0.5f);
Vector3 startPos = transform.position;
Vector3 endPos = target.transform.position;
Quaternion targetRot = target.transform.rotation;
Destroy(target.gameObject);
float elapsed = 0f;
while (elapsed < possessDashDuration)
{
elapsed += Time.unscaledDeltaTime;
float t = Mathf.Clamp01(elapsed / possessDashDuration);
transform.position = Vector3.Lerp(startPos, endPos, t);
yield return null;
}
transform.position = endPos;
Player.Instance.CameraController.SetYaw(targetRot.eulerAngles.y);
ApplyProfile(newProfile, inheritedHealth);
_invulnerableTimer = 0.4f;
_isTransitioning = false;
}
public void EnterSpiritForm(bool ejectImpulse)
{
ApplyProfile(spiritProfile, spiritProfile.maxHealth);
_invulnerableTimer = 0.5f;
if (ejectImpulse && Player.Instance.Movement != null)
{
Player.Instance.Movement.AddVerticalImpulse(8f);
}
}
public void ApplyProfile(BodyProfile profile, float startHealth)
{
CurrentProfile = profile;
CurrentHealth = Mathf.Clamp(startHealth, 1f, profile.maxHealth);
bool isSpirit = profile.bodyClass == BodyClass.Spirit;
Time.timeScale = isSpirit ? spiritTimeScale : 1f;
Time.fixedDeltaTime = 0.02f * Time.timeScale;
Player.Instance.Movement.ApplyProfile(profile);
Player.Instance.CameraController.ApplyProfile(profile);
Player.Instance.Combat.ApplyProfile(profile);
Player.Instance.Sound.SetFootstepPitch(profile.footstepPitch);
}
public void TakeDamage(float amount)
{
if (_invulnerableTimer > 0f || _isTransitioning) return;
CurrentHealth -= amount;
if (CurrentHealth <= 0f)
{
if (!IsInSpiritForm)
{
Debug.Log("Носитель уничтожен! Выброс в форму Духа!");
EnterSpiritForm(true);
}
else
{
CurrentHealth = 0f;
Debug.Log("ДУХ УНИЧТОЖЕН! ИГРА ОКОНЧЕНА.");
EnterSpiritForm(false);
}
}
}
private void OnDestroy()
{
if (_zoneSphere != null) Destroy(_zoneSphere);
Time.timeScale = 1f;
Time.fixedDeltaTime = 0.02f;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 246649c648e14696bc2cac61522a8d66
timeCreated: 1792605158
@@ -17,25 +17,25 @@ namespace _Project.Scripts.PlayerUtils
[Header("Звуки Оружия")]
[SerializeField] private AudioClip shootSound;
private float _baseFootstepPitch = 1f;
private void Reset()
{
// Автоматически подцепит AudioSource при добавлении скрипта на объект
audioSource = GetComponent<AudioSource>();
}
public void SetFootstepPitch(float pitch) => _baseFootstepPitch = pitch;
public void PlayFootstep(bool isSprinting)
{
if (footstepSounds == null || footstepSounds.Length == 0) return;
int randomIndex = Random.Range(0, footstepSounds.Length);
// Немного меняем высоту звука для разнообразия
audioSource.pitch = Random.Range(0.9f, 1.1f);
audioSource.pitch = _baseFootstepPitch * Random.Range(0.92f, 1.08f);
float volume = isSprinting ? 0.6f : 0.4f;
audioSource.PlayOneShot(footstepSounds[randomIndex], volume);
audioSource.pitch = 1f; // Сбрасываем питч обратно
audioSource.pitch = 1f;
}
public void PlayJump()
+32 -25
View File
@@ -5,49 +5,56 @@ namespace _Project.Scripts.PlayerUtils
public class PlayerUI : MonoBehaviour
{
[Header("Настройки Интерфейса")]
[SerializeField] private bool showSpeedometer = true;
[SerializeField] private bool showHUD = true;
private PlayerMovement movement;
private PlayerPossession possession;
private void Start()
{
// Берем ссылку на компонент передвижения через фасад Player
movement = Player.Instance.Movement;
possession = Player.Instance.Possession;
}
private void OnGUI()
{
if (!showSpeedometer || movement == null) return;
if (!showHUD || movement == null) return;
// Читаем публичное свойство скорости (мы добавим его ниже)
float speed = movement.CurrentSpeed;
float csUnits = speed * 38.5f;
GUIStyle style = new GUIStyle
{
fontSize = 24,
fontStyle = FontStyle.Bold
};
GUIStyle style = new GUIStyle { fontSize = 22, fontStyle = FontStyle.Bold };
string state = "";
if (movement.IsSliding) { style.normal.textColor = Color.yellow; state = " [SLIDE]"; }
else if (!movement.IsGrounded) { style.normal.textColor = Color.green; state = " [AIR]"; }
else style.normal.textColor = Color.white;
// Настраиваем цвет и текст состояния
if (movement.IsSliding)
{
style.normal.textColor = Color.yellow;
state = " [SLIDE]";
}
else if (!movement.IsGrounded)
{
style.normal.textColor = Color.green;
state = " [AIR]";
}
else
{
style.normal.textColor = Color.white;
}
GUI.Label(new Rect(30, 30, 600, 40), $"Speed: {speed:F1} m/s ({csUnits:F0} u/s){state}", style);
GUI.Label(new Rect(30, 30, 500, 50), $"Speed: {speed:F1} m/s ({csUnits:F0} u/s){state}", style);
if (possession != null && possession.CurrentProfile != null)
{
style.normal.textColor = possession.IsInSpiritForm ? Color.cyan : Color.green;
string bodyInfo = $"Форма: {possession.CurrentProfile.displayName} | HP: {possession.CurrentHealth:F0}/{possession.MaxHealth:F0}";
if (!possession.IsInSpiritForm) bodyInfo += " ([Q] Покинуть тело)";
GUI.Label(new Rect(30, 65, 800, 40), bodyInfo, style);
if (possession.AimedEnemy != null)
{
if (possession.IsTargetInPossessZone)
{
style.normal.textColor = Color.cyan;
GUI.Label(new Rect(Screen.width / 2f - 160f, Screen.height / 2f + 40f, 450f, 40f),
$"[E] ВСЕЛИТЬСЯ: {possession.AimedEnemy.enemyClass}", style);
}
else
{
style.normal.textColor = new Color(1f, 0.5f, 0.5f);
GUI.Label(new Rect(Screen.width / 2f - 180f, Screen.height / 2f + 40f, 500f, 40f),
$"ДАЛЕКО — ВОЙДИ В СФЕРУ ({possession.AimedEnemy.enemyClass})", style);
}
}
}
}
}
}