Essentials + extra crap

Loadings
Startups
Movement
Camera
This commit is contained in:
ThomasCharester committed 2026-01-12 18:43:51 +03:00
1 parent 662f4a1d05
commit 5f5ace1b52
734 files changed
+107323 -1713

No files matched your search

@@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Code.Infrastructure.Configs;
using Cysharp.Threading.Tasks;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using Object = UnityEngine.Object;
namespace Code.Infrastructure.Camera
{
public class CameraFactory : IDisposable
{
private AsyncOperationHandle<GameCameraConfig> _configHandle;
private GameCameraConfig _config;
private AssetReference _gameCameraConfigReference;
private AsyncOperationHandle<IList<CameraSettingsConfig>> _settingsConfigsHandle;
private Dictionary<CameraMode, CameraSettingsConfig> _settingsConfigs;
private string _cameraConfigsLabel;
private EventBus.EventBus _eventBus;
private UnityEngine.Camera _camera;
private IDisposable _disposableImplementation;
public CameraFactory(IConfigLocator configLocator, EventBus.EventBus eventBus)
{
_gameCameraConfigReference = configLocator.TryGetConfigAssetReference<GameCameraConfig>();
_cameraConfigsLabel = configLocator.TryGetManyConfigAssetReferences<CameraSettingsConfig>();
_eventBus = eventBus;
}
public async UniTaskVoid CreateCameraStateMachine(CameraStateMachine stateMachine)
{
_settingsConfigsHandle = Addressables
.LoadAssetsAsync<CameraSettingsConfig>(_cameraConfigsLabel, null, Addressables.MergeMode.Union);
await _settingsConfigsHandle.ToUniTask();
_settingsConfigs = _settingsConfigsHandle.Result.ToDictionary(x => x.cameraMode);
_configHandle = Addressables.LoadAssetAsync<GameCameraConfig>(_gameCameraConfigReference);
await _configHandle.ToUniTask();
_config = _configHandle.Result;
var cameraObject = await Addressables.InstantiateAsync(_config.Camera).ToUniTask();
_camera = cameraObject.GetComponent<UnityEngine.Camera>();
cameraObject.GetComponent<CameraStateMachineRunner>().StateMachine = stateMachine;
Object.DontDestroyOnLoad(cameraObject);
_eventBus.RaiseEvent<ICameraInitializedHandle>(x => x.CameraInitialized(new(_camera, _settingsConfigs)));
}
public void Dispose()
{
Addressables.Release(_configHandle);
Addressables.Release(_settingsConfigsHandle);
Addressables.ReleaseInstance(_camera.gameObject);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 4c05e01628b742be94dfd0bbbdfb87fa
timeCreated: 1767302222
@@ -0,0 +1,38 @@
using Code.Infrastructure.Generators;
using UnityEngine;
namespace Code.Infrastructure.Camera
{
[Config("Configs/Camera/CameraSettings", true)]
public class CameraSettings
{
// Расстояния от персонажа до камеры
[ToConfig] public float defaultDistance = 6f; // Стандартное расстояние камеры от цели
[ToConfig] public float minDistance = 3f; // Минимальное расстояние при зуме
[ToConfig] public float maxDistance = 10f; // Максимальное расстояние при зуме
[ToConfig] public float distanceMovementSpeed = 5f; // Множитель скорости изменения дистанции при зуме
// Скорость поворота камеры
[ToConfig] public float rotationSpeed = 0.3f;
[ToConfig] public float rotationSharpness = 100f; // Коэффициент плавности вращения камеры (чем выше - тем резче)
[ToConfig] public float followSharpness = 100f; // Коэффициент плавности следования за движущейся целью (чем выше - тем резче)
[ToConfig] public float minVerticalAngle = -70f; // Минимальный угол наклона камеры (вниз)
[ToConfig] public float maxVerticalAngle = 70f; // Максимальный угол наклона камеры (вверх)
[ToConfig] public float defaultVerticalAngle = 10f; // Стандартный угол наклона камеры
[ToConfig] public float fov = 60; // Комментарии оставляет только нейросеть и долбаёбы, никому и так не будет понятно, что ты высрал
[ToConfig] public CameraMode cameraMode;
// Позиция следования по умолчанию
[ToConfig] public Vector3 defaultFollowPosition = Vector3.zero;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 5442de773645443b99f8b0733199a854
timeCreated: 1766657458
@@ -0,0 +1,54 @@
using System.Collections.Generic;
using Code.Infrastructure.EventBus;
using Code.Infrastructure.Generators;
using Code.Infrastructure.Input;
using Reflex.Attributes;
using UnityEngine.AddressableAssets;
namespace Code.Infrastructure.Camera
{
public enum CameraMode
{
None,
FirstPerson,
Static,
Cinematic
}
[Config("Configs/Camera/CameraConfig")]
public class GameCamera
{
[ToConfig] public AssetReference Camera;
}
public interface ICameraInitializedHandle : IGlobalSubscriber
{
void CameraInitialized(CameraStateMachineContext.CameraLoadedData data);
}
public class CameraStateMachineContext
{
public class CameraLoadedData
{
public UnityEngine.Camera Camera;
public Dictionary<CameraMode, CameraSettingsConfig> SettingsConfigs;
public CameraLoadedData(UnityEngine.Camera camera, Dictionary<CameraMode, CameraSettingsConfig> settingsConfigs)
{
Camera = camera;
SettingsConfigs = settingsConfigs;
}
}
public CameraLoadedData cameraLoadedData;
[Inject] public IInputService InputService;
[Inject] public EventBus.EventBus EventBus;
}
[Generators.StateMachine(typeof(CameraStateMachineContext), typeof(CameraMode))]
public partial class CameraStateMachine
{
public UnityEngine.Camera Camera => StateMachineContext.cameraLoadedData.Camera;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: b220b02510c34ea08257cc951d949fd7
timeCreated: 1761671720
@@ -0,0 +1,20 @@
using Code.Infrastructure.Camera.CameraStates;
using UnityEngine;
namespace Code.Infrastructure.Camera
{
public class CameraStateMachineRunner : MonoBehaviour
{
public CameraStateMachine StateMachine;
private void Update()
{
((BaseCameraState)StateMachine.CurrentBaseState).Update();
}
private void LateUpdate()
{
((BaseCameraState)StateMachine.CurrentBaseState).LateUpdate();
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 293de8ebc2f54fa097ba2f1be8c8ed41
timeCreated: 1767277431
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d7399e433dff42a185f62d79b546b059
timeCreated: 1761671908
@@ -0,0 +1,48 @@
using Code.Infrastructure.StateMachine;
using UnityEngine;
namespace Code.Infrastructure.Camera.CameraStates
{
// [State(typeof(CameraMode),typeof(CameraStateMachineContext))]
public abstract class BaseCameraState : BaseState<CameraMode, CameraStateMachineContext>
{
protected EventBus.EventBus _eventBus;
// Трансформ объекта, за которым следует камера
protected Transform FollowTransform;
// Позиция следования: текущая сглаженная позиция и горизонтальное направление камеры
protected Vector3 CurrentFollowPosition;
// Целевой вертикальный угол камеры (наклон вверх/вниз)
protected float TargetVerticalAngle;
// Текущая и целевая дистанция камеры от цели
protected float CurrentDistance, TargetDistance;
// Исходные значения дистанции для восстановления
protected float OriginalDefaultDistance, OriginalMinDistance, OriginalMaxDistance;
// Горизонтальное направление камеры (проекция forward на плоскость)
protected Vector3 PlanarDirection { get; set; }
protected BaseCameraState(CameraStateMachineContext context, EventBus.EventBus eventBus) : base(context, eventBus)
{
_eventBus = eventBus;
}
// Основной метод обновления камеры, вызываемый извне каждый кадр
protected void UpdateWithInput(float deltaTime, Vector3 rotationInput)
{
// Обработка ввода и позиционирования
HandleRotationInput(deltaTime, rotationInput, out var targetRotation);
HandlePosition(deltaTime , targetRotation);
}
protected abstract void HandlePosition(float deltaTime, object o);
protected abstract void HandleRotationInput(float deltaTime, Vector3 rotationInput, out Quaternion q);
public abstract void Update();
public abstract void LateUpdate();
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 7901175f2c0646fda8741c4c269ce54b
timeCreated: 1767127681
@@ -0,0 +1,110 @@
using Code.Example.Liminal.Player;
using Code.Infrastructure.Generators;
using Code.Infrastructure.Input;
using UnityEngine;
using UnityEngine.InputSystem;
namespace Code.Infrastructure.Camera.CameraStates
{
[State(typeof(CameraMode),typeof(CameraStateMachineContext), true)]
public partial class FirstPersonCameraState : BaseCameraState
{
private CameraSettingsConfig _settings;
public FirstPersonCameraState(CameraStateMachineContext context, EventBus.EventBus eventBus) : base(context, eventBus)
{
}
public override CameraMode myState => CameraMode.FirstPerson;
protected override void OnEnterState()
{
_settings = Context.cameraLoadedData.SettingsConfigs[myState];
Context.InputService.BindActionPerformed((int)ActionMappings.Gameplay, (int) GameplayActions.Look, OnLookPerformed);
Context.InputService.BindActionCancel((int)ActionMappings.Gameplay, (int) GameplayActions.Look, OnLookCanceled);
}
protected override void HandleRotationInput(float deltaTime, Vector3 rotationInput, out Quaternion targetRotation)
{
// Вращение вокруг вертикальной оси (горизонтальный поворот)
var rotationFromInput = Quaternion.Euler(Vector3.up * (rotationInput.x * _settings.rotationSpeed));
PlanarDirection = rotationFromInput * PlanarDirection;
var planarRotation = Quaternion.LookRotation(PlanarDirection, FollowTransform.up);
// Вращение вокруг горизонтальной оси (вертикальный наклон)
TargetVerticalAngle -= rotationInput.y * _settings.rotationSpeed;
TargetVerticalAngle = Mathf.Clamp(TargetVerticalAngle, _settings.minVerticalAngle, _settings.maxVerticalAngle);
var verticalRotation = Quaternion.Euler(TargetVerticalAngle, 0, 0);
// Интерполяция к целевому вращению для плавности
targetRotation = Quaternion.Slerp(Context.cameraLoadedData.Camera.transform.rotation, planarRotation * verticalRotation, deltaTime * _settings.rotationSharpness);
// Применение финального вращения
Context.cameraLoadedData.Camera.transform.rotation = targetRotation;
}
protected override void OnExitState()
{
}
protected override void HandlePosition(float deltaTime, object targetRotation)
{
// Плавное следование за целью с использованием экспоненциального сглаживания
// CurrentFollowPosition = Vector3.Lerp(CurrentFollowPosition, FollowTransform.position, 1f - Mathf.Exp(-_settings.followSharpness * deltaTime));
// В FirstPerson режиме камера находится прямо на позиции цели Да ну нахуй чё правда пиздец
// var targetPosition = CurrentFollowPosition;
// Установка финальной позиции камеры Да ну нахуй чё правда пиздец
Context.cameraLoadedData.Camera.transform.position = FollowTransform.position;
}
private Vector2 _lookInput;
private void OnLookPerformed(InputAction.CallbackContext context)
{
_lookInput = context.ReadValue<Vector2>();
}
private void OnLookCanceled(InputAction.CallbackContext context)
{
_lookInput = Vector2.zero;
}
public override void Update()
{
}
public override void LateUpdate()
{
// Обновляем камеру только если есть цель для следования
// if (FollowTransform)
// {
// UpdateWithInput(Time.deltaTime, _lookInput);
// }
if (_playerMovementController)
{
UpdateWithInput(Time.deltaTime, _lookInput);
_playerMovementController.SetCameraRotation(Context.cameraLoadedData.Camera.transform.rotation);
}
}
public void SetFollowTransform(Transform t)
{
FollowTransform = t;
CurrentFollowPosition = t.position;
PlanarDirection = t.forward; // Начальное направление совпадает с направлением цели
}
private PlayerMovementController _playerMovementController;
public void SetPlayer(PlayerMovementController playerMovementController)
{
_playerMovementController = playerMovementController;
FollowTransform = _playerMovementController.PlayerHeadPoint;
CurrentFollowPosition = _playerMovementController.PlayerHeadPoint.position;
PlanarDirection = _playerMovementController.PlayerHeadPoint.forward; // Начальное направление совпадает с направлением цели
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 850f6325ab66480e9f7d1c03dbb37030
timeCreated: 1767346203
@@ -0,0 +1,40 @@
using Code.Infrastructure.Generators;
using UnityEngine;
namespace Code.Infrastructure.Camera.CameraStates
{
[State(typeof(CameraMode),typeof(CameraStateMachineContext), true)]
public partial class NoneCameraState : BaseCameraState
{
public NoneCameraState(CameraStateMachineContext context, EventBus.EventBus eventBus) : base(context, eventBus)
{
}
public override CameraMode myState => CameraMode.None;
protected override void OnEnterState()
{
}
protected override void OnExitState()
{
}
protected override void HandlePosition(float deltaTime, object targetRotation)
{
throw new System.NotImplementedException();
}
protected override void HandleRotationInput(float deltaTime, Vector3 rotationInput, out Quaternion q)
{
throw new System.NotImplementedException();
}
public override void Update()
{
}
public override void LateUpdate()
{
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: cb14de48ff13488c8edb4431ac34e5be
timeCreated: 1767301090