ошибки поворота, прицела
This commit is contained in:
1 parent
202a894140
commit
da648df1d9
200 files changed
+31969
-629
No files matched your search
@@ -4,6 +4,7 @@ using UnityEngine.AI;
|
||||
public class BlindMutantAI : MonoBehaviour
|
||||
{
|
||||
private NavMeshAgent agent;
|
||||
private Animator animator;
|
||||
|
||||
[Header("Настройки скорости")]
|
||||
public float walkSpeed = 2f;
|
||||
@@ -30,6 +31,7 @@ public class BlindMutantAI : MonoBehaviour
|
||||
{
|
||||
agent = GetComponent<NavMeshAgent>();
|
||||
agent.speed = walkSpeed;
|
||||
animator = GetComponentInChildren<Animator>();
|
||||
|
||||
// Автоматически находим игрока на сцене
|
||||
var playerObj = FindAnyObjectByType<PlayerHealth>();
|
||||
@@ -46,6 +48,8 @@ public class BlindMutantAI : MonoBehaviour
|
||||
|
||||
void Update()
|
||||
{
|
||||
UpdateAnimator();
|
||||
|
||||
// 1. Поведение при активном преследовании игрока
|
||||
if (targetPlayer != null)
|
||||
{
|
||||
@@ -60,6 +64,13 @@ public class BlindMutantAI : MonoBehaviour
|
||||
HandlePatrolAndInvestigation();
|
||||
}
|
||||
|
||||
private void UpdateAnimator()
|
||||
{
|
||||
if (animator == null) return;
|
||||
float currentSpeed = agent != null && agent.enabled ? agent.velocity.magnitude : 0f;
|
||||
animator.SetFloat("Speed", currentSpeed);
|
||||
}
|
||||
|
||||
private void HandlePlayerChaseAndAttack()
|
||||
{
|
||||
if (targetPlayerHealth != null && targetPlayerHealth.IsDead)
|
||||
@@ -94,6 +105,10 @@ public class BlindMutantAI : MonoBehaviour
|
||||
if (Time.time >= nextAttackTime)
|
||||
{
|
||||
nextAttackTime = Time.time + attackCooldown;
|
||||
if (animator != null)
|
||||
{
|
||||
animator.SetTrigger("Attack");
|
||||
}
|
||||
if (targetPlayerHealth != null)
|
||||
{
|
||||
targetPlayerHealth.TakeDamage(attackDamage);
|
||||
@@ -193,6 +208,10 @@ public class BlindMutantAI : MonoBehaviour
|
||||
|
||||
public void OnDamagedByPlayer(Transform player)
|
||||
{
|
||||
if (animator != null)
|
||||
{
|
||||
animator.SetTrigger("GetHit");
|
||||
}
|
||||
EngagePlayer(player);
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -10,7 +10,7 @@ public static class SetupPlayerAnimatorLayers
|
||||
private const string IdleFbxPath = "Assets/Kevin Iglesias/Human Animations/Animations/Male/Idles/HumanM@Idle01.fbx";
|
||||
private const string WalkFbxPath = "Assets/Kevin Iglesias/Human Animations/Animations/Male/Movement/Walk/HumanM@Walk01_Forward.fbx";
|
||||
private const string SprintFbxPath = "Assets/Kevin Iglesias/Human Animations/Animations/Male/Movement/Sprint/HumanM@Sprint01_Forward.fbx";
|
||||
private const string AttackFbxPath = "Assets/Brawler Animations/Animations/Atk_P_1.fbx";
|
||||
private const string AttackFbxPath = "Assets/Brawler Animations Sample/Animations/Atk_P_1.fbx";
|
||||
private const string GunAimFbxPath = "Assets/Kevin Iglesias/Human Animations/Animations/Male/Combat/Gun/HumanM@Gun_Aim01.fbx";
|
||||
private const string GunShootFbxPath = "Assets/Kevin Iglesias/Human Animations/Animations/Male/Combat/Gun/HumanM@Gun_Aim01_Shoot01.fbx";
|
||||
private const string GunReloadFbxPath = "Assets/Kevin Iglesias/Human Animations/Animations/Male/Combat/Gun/HumanM@Gun_Reload01.fbx";
|
||||
@@ -80,7 +80,7 @@ public static class SetupPlayerAnimatorLayers
|
||||
locomotionState.motion = blendTree;
|
||||
baseSm.defaultState = locomotionState;
|
||||
|
||||
// Создаем Melee Attack State
|
||||
// Создаем Melee Attack State в Base Layer
|
||||
var attackClip = FindClip(AttackFbxPath);
|
||||
if (attackClip != null)
|
||||
{
|
||||
@@ -98,8 +98,12 @@ public static class SetupPlayerAnimatorLayers
|
||||
fromAttack.exitTime = 0.85f;
|
||||
fromAttack.duration = 0.15f;
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogError($"[SetupPlayerAnimatorLayers] Attack clip not found at path: {AttackFbxPath}!");
|
||||
}
|
||||
|
||||
// 3. UpperBody Layer (для удержания оружия, выстрела, перезарядки)
|
||||
// 3. UpperBody Layer (для удержания оружия, выстрела, перезарядки и рукопашного удара при оружии)
|
||||
var upperMask = AssetDatabase.LoadAssetAtPath<AvatarMask>(UpperMaskPath);
|
||||
if (upperMask == null)
|
||||
{
|
||||
@@ -128,9 +132,11 @@ public static class SetupPlayerAnimatorLayers
|
||||
var gunShootClip = FindClip(GunShootFbxPath);
|
||||
var gunReloadClip = FindClip(GunReloadFbxPath);
|
||||
|
||||
AnimatorState gunAimState = null;
|
||||
|
||||
if (gunAimClip != null)
|
||||
{
|
||||
var gunAimState = upperSm.AddState("Gun_Aim", new Vector3(250, 150, 0));
|
||||
gunAimState = upperSm.AddState("Gun_Aim", new Vector3(250, 150, 0));
|
||||
gunAimState.motion = gunAimClip;
|
||||
|
||||
// Empty <-> Gun_Aim
|
||||
@@ -179,6 +185,34 @@ public static class SetupPlayerAnimatorLayers
|
||||
}
|
||||
}
|
||||
|
||||
// Также добавляем Attack в UpperBody Layer, чтобы при удержании оружия (вес UpperBody=1) анимация удара не блокировалась
|
||||
if (attackClip != null)
|
||||
{
|
||||
var upperAttackState = upperSm.AddState("Attack", new Vector3(500, 0, 0));
|
||||
upperAttackState.motion = attackClip;
|
||||
upperAttackState.speed = 1.15f;
|
||||
|
||||
var toUpperAttack = upperSm.AddAnyStateTransition(upperAttackState);
|
||||
toUpperAttack.AddCondition(AnimatorConditionMode.If, 0f, "Attack");
|
||||
toUpperAttack.duration = 0.08f;
|
||||
toUpperAttack.canTransitionToSelf = false;
|
||||
|
||||
if (gunAimState != null)
|
||||
{
|
||||
var toAimAfterAttack = upperAttackState.AddTransition(gunAimState);
|
||||
toAimAfterAttack.AddCondition(AnimatorConditionMode.If, 0f, "HasGun");
|
||||
toAimAfterAttack.hasExitTime = true;
|
||||
toAimAfterAttack.exitTime = 0.85f;
|
||||
toAimAfterAttack.duration = 0.15f;
|
||||
}
|
||||
|
||||
var toEmptyAfterAttack = upperAttackState.AddTransition(emptyState);
|
||||
toEmptyAfterAttack.AddCondition(AnimatorConditionMode.IfNot, 0f, "HasGun");
|
||||
toEmptyAfterAttack.hasExitTime = true;
|
||||
toEmptyAfterAttack.exitTime = 0.85f;
|
||||
toEmptyAfterAttack.duration = 0.15f;
|
||||
}
|
||||
|
||||
controller.layers = layers;
|
||||
|
||||
EditorUtility.SetDirty(controller);
|
||||
|
||||
@@ -30,8 +30,38 @@ public class MutantHealth : MonoBehaviour
|
||||
|
||||
if (currentHealth <= 0)
|
||||
{
|
||||
Debug.Log("МУТАНТ УМЕР!");
|
||||
Destroy(gameObject);
|
||||
Die();
|
||||
}
|
||||
}
|
||||
|
||||
private void Die()
|
||||
{
|
||||
Debug.Log("МУТАНТ УМЕР!");
|
||||
var anim = GetComponentInChildren<Animator>();
|
||||
if (anim != null)
|
||||
{
|
||||
anim.SetBool("IsDead", true);
|
||||
anim.SetTrigger("Die");
|
||||
}
|
||||
|
||||
if (mutantAI != null)
|
||||
{
|
||||
mutantAI.enabled = false;
|
||||
}
|
||||
|
||||
var agent = GetComponent<UnityEngine.AI.NavMeshAgent>();
|
||||
if (agent != null)
|
||||
{
|
||||
agent.isStopped = true;
|
||||
agent.enabled = false;
|
||||
}
|
||||
|
||||
var col = GetComponent<Collider>();
|
||||
if (col != null)
|
||||
{
|
||||
col.enabled = false;
|
||||
}
|
||||
|
||||
Destroy(gameObject, 3.5f);
|
||||
}
|
||||
}
|
||||
@@ -84,8 +84,8 @@ public class PlayerAttack : MonoBehaviour
|
||||
if (camFwd.sqrMagnitude > 0.001f)
|
||||
{
|
||||
attackDir = camFwd.normalized;
|
||||
// Поворачиваем персонажа лицом к направлению атаки (прицелу)
|
||||
transform.rotation = Quaternion.LookRotation(attackDir);
|
||||
// Быстро и плавно поворачиваем персонажа лицом к направлению атаки (прицелу)
|
||||
GetComponent<PlayerMovement>()?.SnapToAim(attackCooldown);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -143,23 +143,43 @@ public class PlayerGun : MonoBehaviour
|
||||
// (ЛКМ в этом случае используется скриптом PlayerAttack для рукопашного удара)
|
||||
if (!isGunEquipped) return;
|
||||
|
||||
// 4. Выстрел (ЛКМ)
|
||||
// 4. Прицеливание (ПКМ) при оружии в руках
|
||||
if (Mouse.current.rightButton.isPressed)
|
||||
{
|
||||
FaceAimTarget(0.15f);
|
||||
}
|
||||
|
||||
// 5. Выстрел (ЛКМ)
|
||||
bool shootInput = isAutomatic
|
||||
? Mouse.current.leftButton.isPressed
|
||||
: Mouse.current.leftButton.wasPressedThisFrame;
|
||||
|
||||
if (shootInput)
|
||||
{
|
||||
FaceAimTarget(0.6f);
|
||||
TryShoot();
|
||||
}
|
||||
|
||||
// 5. Перезарядка (Клавиша R)
|
||||
// 6. Перезарядка (Клавиша R)
|
||||
if (Keyboard.current.rKey.wasPressedThisFrame)
|
||||
{
|
||||
TryStartReload();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Активирует быстрый и плавный поворот персонажа к направлению прицела камеры (перекрестия)
|
||||
/// и активирует стрейф-режим перемещения через PlayerMovement.
|
||||
/// </summary>
|
||||
public void FaceAimTarget(float duration = 0.5f)
|
||||
{
|
||||
PlayerMovement movement = GetComponent<PlayerMovement>();
|
||||
if (movement != null)
|
||||
{
|
||||
movement.SnapToAim(duration);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Переключение взятия/убирания оружия
|
||||
/// </summary>
|
||||
@@ -256,6 +276,9 @@ public class PlayerGun : MonoBehaviour
|
||||
|
||||
private void ExecuteShot()
|
||||
{
|
||||
// Поворачиваем персонажа лицом к прицелу перед вычислением траектории выстрела
|
||||
FaceAimTarget(0.6f);
|
||||
|
||||
// Звук выстрела
|
||||
if (audioSource != null && shootSound != null)
|
||||
{
|
||||
|
||||
@@ -10,8 +10,11 @@ public class PlayerMovement : MonoBehaviour
|
||||
public float sneakSpeed = 1.5f; // Тактический шаг (Ctrl)
|
||||
|
||||
[Header("Настройки вращения")]
|
||||
public float turnSmoothTime = 0.1f; // Плавность поворота модельки
|
||||
public float turnSmoothTime = 0.1f; // Плавность поворота модельки при свободном беге
|
||||
[Tooltip("Плавность поворота к прицелу при стрельбе/прицеливании (быстро, но без телепорта)")]
|
||||
public float aimTurnSmoothTime = 0.05f;
|
||||
private float turnSmoothVelocity;
|
||||
private float aimTurnSmoothVelocity;
|
||||
|
||||
[Header("Камера")]
|
||||
public Transform cam; // Ссылка на главную камеру
|
||||
@@ -23,10 +26,16 @@ public class PlayerMovement : MonoBehaviour
|
||||
private Vector3 velocity;
|
||||
private float gravity = -9.81f;
|
||||
private float currentAnimSpeed = 0f;
|
||||
private float aimLockTimer = 0f;
|
||||
|
||||
public bool IsAimLocked => aimLockTimer > 0f;
|
||||
|
||||
void Start()
|
||||
{
|
||||
controller = GetComponent<CharacterController>();
|
||||
if (cam == null && Camera.main != null)
|
||||
cam = Camera.main.transform;
|
||||
|
||||
if (animator == null)
|
||||
animator = GetComponentInChildren<Animator>();
|
||||
|
||||
@@ -41,6 +50,23 @@ public class PlayerMovement : MonoBehaviour
|
||||
Cursor.visible = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Активирует быстрый плавный разворот персонажа к прицелу камеры (для стрельбы/ударов)
|
||||
/// и удерживает режим стрейфа на заданное время.
|
||||
/// </summary>
|
||||
public void SnapToAim(float lockDuration = 0.5f)
|
||||
{
|
||||
if (cam == null && Camera.main != null)
|
||||
cam = Camera.main.transform;
|
||||
|
||||
if (aimLockTimer <= 0f)
|
||||
{
|
||||
aimTurnSmoothVelocity = 0f;
|
||||
}
|
||||
|
||||
aimLockTimer = Mathf.Max(aimLockTimer, lockDuration);
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
HandleMovement();
|
||||
@@ -48,6 +74,18 @@ public class PlayerMovement : MonoBehaviour
|
||||
|
||||
void HandleMovement()
|
||||
{
|
||||
if (cam == null && Camera.main != null)
|
||||
cam = Camera.main.transform;
|
||||
|
||||
if (aimLockTimer > 0f)
|
||||
{
|
||||
aimLockTimer -= Time.deltaTime;
|
||||
if (aimLockTimer <= 0f)
|
||||
{
|
||||
turnSmoothVelocity = 0f;
|
||||
}
|
||||
}
|
||||
|
||||
// Гравитация
|
||||
if (controller.isGrounded && velocity.y < 0)
|
||||
{
|
||||
@@ -76,12 +114,37 @@ public class PlayerMovement : MonoBehaviour
|
||||
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
|
||||
bool isMoving = direction.magnitude >= 0.1f;
|
||||
|
||||
if (isMoving)
|
||||
if (aimLockTimer > 0f)
|
||||
{
|
||||
// Вычисляем угол поворота с учетом направления камеры
|
||||
// При стрельбе/прицеливании персонаж быстро и плавно поворачивается в сторону прицела камеры
|
||||
if (cam != null)
|
||||
{
|
||||
float targetAngle = cam.eulerAngles.y;
|
||||
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref aimTurnSmoothVelocity, aimTurnSmoothTime);
|
||||
transform.rotation = Quaternion.Euler(0f, angle, 0f);
|
||||
}
|
||||
|
||||
// Перемещение работает в режиме стрейфа относительно камеры (нажатие назад = отступать спиной к камере)
|
||||
if (isMoving && cam != null)
|
||||
{
|
||||
Vector3 camFwd = cam.forward;
|
||||
camFwd.y = 0f;
|
||||
camFwd.Normalize();
|
||||
|
||||
Vector3 camRight = cam.right;
|
||||
camRight.y = 0f;
|
||||
camRight.Normalize();
|
||||
|
||||
Vector3 moveDir = (camFwd * vertical + camRight * horizontal).normalized;
|
||||
controller.Move(moveDir * currentSpeed * Time.deltaTime);
|
||||
}
|
||||
}
|
||||
else if (isMoving)
|
||||
{
|
||||
// Свободный бег: вычисляем угол поворота с учетом направления камеры
|
||||
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
|
||||
|
||||
// Плавно поворачиваем капсулу
|
||||
// Плавно поворачиваем капсулу в сторону бега
|
||||
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
|
||||
transform.rotation = Quaternion.Euler(0f, angle, 0f);
|
||||
|
||||
|
||||
Reference in new issue
Block a user