Первый коммит с LFS.
This commit is contained in:
1 parent
4fcb1e2f24
commit
179816dc4b
5084 files changed
+3714098
-1
No files matched your search
@@ -0,0 +1,93 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
|
||||
public class DoorController : MonoBehaviour, IInteractable
|
||||
{
|
||||
[Header("Settings")]
|
||||
[SerializeField] private float openAngle = 90f;
|
||||
[SerializeField] private float smoothSpeed = 2f;
|
||||
[SerializeField] private bool isLocked = false;
|
||||
|
||||
[Header("Key Settings")]
|
||||
[SerializeField] private ItemData keyRequired;
|
||||
|
||||
private bool _isOpen = false;
|
||||
private Quaternion _closedRotation;
|
||||
private Quaternion _openRotation;
|
||||
private Coroutine _animationCoroutine;
|
||||
|
||||
private void Start()
|
||||
{
|
||||
_closedRotation = transform.localRotation;
|
||||
_openRotation = _closedRotation * Quaternion.Euler(0, openAngle, 0);
|
||||
}
|
||||
|
||||
public void Interact()
|
||||
{
|
||||
if (_isOpen)
|
||||
{
|
||||
Close();
|
||||
}
|
||||
else
|
||||
{
|
||||
TryOpen();
|
||||
}
|
||||
}
|
||||
|
||||
public string GetDescription()
|
||||
{
|
||||
if (isLocked) return "Заперто (Нужен ключ)";
|
||||
return _isOpen ? "Закрыть" : "Открыть";
|
||||
}
|
||||
|
||||
private void TryOpen()
|
||||
{
|
||||
if (isLocked)
|
||||
{
|
||||
if (keyRequired != null && InventorySystem.Instance.HasItem(keyRequired))
|
||||
{
|
||||
Debug.Log("Ключ подошел! Дверь открыта.");
|
||||
isLocked = false;
|
||||
Open();
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Log("Нужен ключ!");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Open();
|
||||
}
|
||||
}
|
||||
|
||||
private void Open()
|
||||
{
|
||||
_isOpen = true;
|
||||
StopAnimation();
|
||||
_animationCoroutine = StartCoroutine(AnimateDoor(_openRotation));
|
||||
}
|
||||
|
||||
private void Close()
|
||||
{
|
||||
_isOpen = false;
|
||||
StopAnimation();
|
||||
_animationCoroutine = StartCoroutine(AnimateDoor(_closedRotation));
|
||||
}
|
||||
|
||||
private void StopAnimation()
|
||||
{
|
||||
if (_animationCoroutine != null) StopCoroutine(_animationCoroutine);
|
||||
}
|
||||
|
||||
// Универсальная корутина для плавного вращения
|
||||
private IEnumerator AnimateDoor(Quaternion targetRotation)
|
||||
{
|
||||
while (Quaternion.Angle(transform.localRotation, targetRotation) > 0.1f)
|
||||
{
|
||||
transform.localRotation = Quaternion.Slerp(transform.localRotation, targetRotation, Time.deltaTime * smoothSpeed);
|
||||
yield return null;
|
||||
}
|
||||
transform.localRotation = targetRotation;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2b2c269cafcd4f7eaccd52b73879742c
|
||||
timeCreated: 1764357159
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d0b7ed00410d48b5b1bbb8cdc7badc60
|
||||
timeCreated: 1764803820
|
||||
@@ -0,0 +1,37 @@
|
||||
|
||||
using UnityEngine;
|
||||
|
||||
[RequireComponent(typeof(Collider))]
|
||||
public class EventTriggerOnCollision : MonoBehaviour
|
||||
{
|
||||
[Tooltip("Тег объекта, который должен активировать триггер.")] [SerializeField]
|
||||
private string _targetTag;
|
||||
|
||||
[Tooltip("Событие, которое будет вызвано при входе в триггер.")]
|
||||
[SerializeField] private GameEvent _eventToRaise;
|
||||
|
||||
[Tooltip("Если true, событие будет срабатывать только один раз.")]
|
||||
[SerializeField] private bool _triggerOnce = true;
|
||||
|
||||
private bool _hasBeenTriggered = false;
|
||||
|
||||
private void OnTriggerEnter(Collider other)
|
||||
{
|
||||
if (_hasBeenTriggered && _triggerOnce)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (other.CompareTag(_targetTag))
|
||||
{
|
||||
_eventToRaise.Raise();
|
||||
_hasBeenTriggered = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnValidate()
|
||||
{
|
||||
// Убедимся, что коллайдер на объекте является триггером
|
||||
GetComponent<Collider>().isTrigger = true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f783bdc6f8b240a187af9a15648ae9db
|
||||
timeCreated: 1764803977
|
||||
@@ -0,0 +1,51 @@
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
|
||||
[RequireComponent(typeof(Collider))]
|
||||
public class EventTriggerOnStay : MonoBehaviour
|
||||
{
|
||||
[Tooltip("Тег объекта, который должен активировать триггер.")]
|
||||
[SerializeField] private string _targetTag = "Player";
|
||||
|
||||
[Tooltip("Событие, которое будет вызвано.")]
|
||||
[SerializeField] private GameEvent _eventToRaise;
|
||||
|
||||
[Tooltip("Время в секундах, которое объект должен провести в триггере для срабатывания.")]
|
||||
[SerializeField] private float _timeToStay = 2.0f;
|
||||
|
||||
[Tooltip("Если true, событие будет срабатывать только один раз.")]
|
||||
[SerializeField] private bool _triggerOnce = true;
|
||||
|
||||
private bool _hasBeenTriggered = false;
|
||||
private Coroutine _timerCoroutine;
|
||||
|
||||
private void OnTriggerEnter(Collider other)
|
||||
{
|
||||
if ((_hasBeenTriggered && _triggerOnce) || !other.CompareTag(_targetTag))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Запускаем корутину-таймер
|
||||
_timerCoroutine = StartCoroutine(TimerCoroutine());
|
||||
}
|
||||
|
||||
private void OnTriggerExit(Collider other)
|
||||
{
|
||||
if (other.CompareTag(_targetTag) && _timerCoroutine != null)
|
||||
{
|
||||
// Если игрок покинул зону, останавливаем таймер
|
||||
StopCoroutine(_timerCoroutine);
|
||||
_timerCoroutine = null;
|
||||
}
|
||||
}
|
||||
|
||||
private IEnumerator TimerCoroutine()
|
||||
{
|
||||
yield return new WaitForSeconds(_timeToStay);
|
||||
|
||||
_eventToRaise.Raise();
|
||||
_hasBeenTriggered = true;
|
||||
_timerCoroutine = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b01c76c4d8fd47d993f1f642f964c911
|
||||
timeCreated: 1764807553
|
||||
@@ -0,0 +1,34 @@
|
||||
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
[CreateAssetMenu(menuName = "Game Event", fileName = "New Game Event")]
|
||||
public class GameEvent : ScriptableObject
|
||||
{
|
||||
private readonly List<GameEventListener> _listeners = new List<GameEventListener>();
|
||||
|
||||
public void Raise()
|
||||
{
|
||||
// Проходимся по списку в обратном порядке, на случай если слушатель удалится во время вызова
|
||||
for (int i = _listeners.Count - 1; i >= 0; i--)
|
||||
{
|
||||
_listeners[i].OnEventRaised();
|
||||
}
|
||||
}
|
||||
|
||||
public void RegisterListener(GameEventListener listener)
|
||||
{
|
||||
if (!_listeners.Contains(listener))
|
||||
{
|
||||
_listeners.Add(listener);
|
||||
}
|
||||
}
|
||||
|
||||
public void UnregisterListener(GameEventListener listener)
|
||||
{
|
||||
if (_listeners.Contains(listener))
|
||||
{
|
||||
_listeners.Remove(listener);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e9817517fd364cf9b2e31ce10da6443c
|
||||
timeCreated: 1764803840
|
||||
@@ -0,0 +1,27 @@
|
||||
|
||||
using UnityEngine;
|
||||
using UnityEngine.Events;
|
||||
|
||||
public class GameEventListener : MonoBehaviour
|
||||
{
|
||||
[Tooltip("Событие, на которое нужно отреагировать.")]
|
||||
[SerializeField] private GameEvent _event;
|
||||
|
||||
[Tooltip("Действия, которые выполнятся при срабатывании события.")]
|
||||
[SerializeField] private UnityEvent _response;
|
||||
|
||||
private void OnEnable()
|
||||
{
|
||||
_event.RegisterListener(this);
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
_event.UnregisterListener(this);
|
||||
}
|
||||
|
||||
public void OnEventRaised()
|
||||
{
|
||||
_response.Invoke();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ba281a10cc184e2eb5600908e4c425a2
|
||||
timeCreated: 1764803903
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 1d2b0107be8f4f6782c92dc020428da4
|
||||
timeCreated: 1764805688
|
||||
@@ -0,0 +1,29 @@
|
||||
|
||||
using UnityEngine;
|
||||
|
||||
public class KnifeController : MonoBehaviour
|
||||
{
|
||||
[SerializeField] private Rigidbody[] _knives;
|
||||
[SerializeField] private AudioSource _audioSource;
|
||||
[SerializeField] private AudioClip _fallSound;
|
||||
|
||||
public void DropKnives()
|
||||
{
|
||||
if (_audioSource != null && _fallSound != null)
|
||||
{
|
||||
_audioSource.PlayOneShot(_fallSound);
|
||||
}
|
||||
|
||||
foreach (var knifeRb in _knives)
|
||||
{
|
||||
if (knifeRb != null)
|
||||
{
|
||||
knifeRb.isKinematic = false;
|
||||
knifeRb.useGravity = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Опционально: отключаем этот компонент, чтобы ножи не упали снова
|
||||
// enabled = false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 51ff3fcabb344f16a61de20a3d1f9821
|
||||
timeCreated: 1764805699
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c476224bbdb84a2f9245eec6d91b3c04
|
||||
timeCreated: 1764807553
|
||||
@@ -0,0 +1,50 @@
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
|
||||
[RequireComponent(typeof(AudioSource))]
|
||||
public class TVController : MonoBehaviour
|
||||
{
|
||||
[Header("Компоненты")]
|
||||
[Tooltip("Renderer объекта, представляющего экран телевизора.")]
|
||||
[SerializeField] private Renderer _tvScreenRenderer;
|
||||
[SerializeField] private AudioSource _audioSource;
|
||||
|
||||
[Header("Настройки")]
|
||||
[Tooltip("Звук, который проигрывается при включенном телевизоре.")]
|
||||
[SerializeField] private AudioClip _tvSound;
|
||||
|
||||
[Tooltip("Через сколько секунд после включения телевизор выключится.")]
|
||||
[SerializeField] private float _onDuration = 5.0f;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
// Убедимся, что экран и звук выключены на старте
|
||||
if (_tvScreenRenderer != null)
|
||||
{
|
||||
_tvScreenRenderer.enabled = false;
|
||||
}
|
||||
_audioSource = GetComponent<AudioSource>();
|
||||
}
|
||||
|
||||
// Публичный метод для включения телевизора
|
||||
public void TurnOnAndOffAfterDelay()
|
||||
{
|
||||
StartCoroutine(TVActivationCoroutine());
|
||||
}
|
||||
|
||||
private IEnumerator TVActivationCoroutine()
|
||||
{
|
||||
// Фаза включения
|
||||
Debug.Log("Телевизор включается...");
|
||||
_tvScreenRenderer.enabled = true;
|
||||
_audioSource.PlayOneShot(_tvSound);
|
||||
|
||||
// Ожидание
|
||||
yield return new WaitForSeconds(_onDuration);
|
||||
|
||||
// Фаза выключения
|
||||
Debug.Log("Телевизор выключается...");
|
||||
_tvScreenRenderer.enabled = false;
|
||||
// Звук остановится сам, так как он OneShot. Если звук зациклен, нужно использовать _audioSource.Stop().
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 65c7178ad67848738b96cee7ef3e5f35
|
||||
timeCreated: 1764807553
|
||||
@@ -0,0 +1,5 @@
|
||||
public interface IInteractable
|
||||
{
|
||||
void Interact();
|
||||
string GetDescription();
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d855186207ad4c34b6e95e0959be0ad6
|
||||
timeCreated: 1764356969
|
||||
@@ -0,0 +1,129 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
using Player; // Подключаем для доступа к PlayerController
|
||||
|
||||
[RequireComponent(typeof(Outline))]
|
||||
public class InspectableObject : MonoBehaviour, IInteractable
|
||||
{
|
||||
[Header("Настройки Осмотра")]
|
||||
[Tooltip("Точка перед камерой, куда будет перемещаться объект. Если пусто, будет рассчитано автоматически.")]
|
||||
[SerializeField] private Transform inspectPoint;
|
||||
[Tooltip("Дополнительное смещение позиции объекта в режиме осмотра.")]
|
||||
[SerializeField] private Vector3 positionOffset = Vector3.zero;
|
||||
[Tooltip("Дополнительное вращение объекта в режиме осмотра (в градусах).")]
|
||||
[SerializeField] private Vector3 rotationOffset = Vector3.zero;
|
||||
[Tooltip("Скорость анимации приближения и отдаления.")]
|
||||
[SerializeField] private float animationSpeed = 8f;
|
||||
[Tooltip("Время, которое объект будет находиться перед камерой.")]
|
||||
[SerializeField] private float holdDuration = 3f;
|
||||
[Tooltip("Звук, проигрываемый при начале осмотра.")]
|
||||
[SerializeField] private AudioClip inspectSound;
|
||||
[Tooltip("Текст подсказки для взаимодействия.")]
|
||||
[SerializeField] private string description = "Осмотреть";
|
||||
|
||||
private bool _isInspecting = false;
|
||||
private Vector3 _originalPosition;
|
||||
private Quaternion _originalRotation;
|
||||
private Transform _originalParent;
|
||||
|
||||
private PlayerController _playerController;
|
||||
private AudioSource _audioSource;
|
||||
|
||||
void Start()
|
||||
{
|
||||
_playerController = FindObjectOfType<PlayerController>();
|
||||
|
||||
_audioSource = GetComponent<AudioSource>();
|
||||
if (_audioSource == null)
|
||||
{
|
||||
_audioSource = gameObject.AddComponent<AudioSource>();
|
||||
}
|
||||
|
||||
if (inspectPoint == null)
|
||||
{
|
||||
var mainCamera = Camera.main;
|
||||
if (mainCamera != null)
|
||||
{
|
||||
GameObject generatedPoint = new GameObject($"{name}_InspectPoint");
|
||||
generatedPoint.transform.SetParent(mainCamera.transform);
|
||||
generatedPoint.transform.localPosition = new Vector3(0, 0, 0.8f);
|
||||
generatedPoint.transform.localRotation = Quaternion.identity;
|
||||
inspectPoint = generatedPoint.transform;
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogError("Камера с тэгом 'MainCamera' не найдена! Осмотр объектов может работать некорректно.", this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public string GetDescription()
|
||||
{
|
||||
return _isInspecting ? "" : description;
|
||||
}
|
||||
|
||||
public void Interact()
|
||||
{
|
||||
if (_isInspecting || _playerController == null || inspectPoint == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
StartCoroutine(InspectRoutine());
|
||||
}
|
||||
|
||||
private IEnumerator InspectRoutine()
|
||||
{
|
||||
_isInspecting = true;
|
||||
_playerController.inputLocked = true;
|
||||
|
||||
_originalPosition = transform.position;
|
||||
_originalRotation = transform.rotation;
|
||||
_originalParent = transform.parent;
|
||||
transform.SetParent(null);
|
||||
|
||||
if (inspectSound != null)
|
||||
{
|
||||
_audioSource.PlayOneShot(inspectSound);
|
||||
}
|
||||
|
||||
// *** ГЛАВНОЕ ИЗМЕНЕНИЕ: Рассчитываем целевую позицию и поворот с учетом смещений ***
|
||||
Vector3 targetPosition = inspectPoint.position + inspectPoint.TransformDirection(positionOffset);
|
||||
Quaternion targetRotation = inspectPoint.rotation * Quaternion.Euler(rotationOffset);
|
||||
|
||||
// --- Фаза 1: Приближение к камере ---
|
||||
float journey = 0f;
|
||||
while (journey < 1f)
|
||||
{
|
||||
journey += Time.deltaTime * animationSpeed;
|
||||
transform.position = Vector3.Lerp(_originalPosition, targetPosition, journey);
|
||||
transform.rotation = Quaternion.Slerp(_originalRotation, targetRotation, journey);
|
||||
yield return null;
|
||||
}
|
||||
transform.position = targetPosition;
|
||||
transform.rotation = targetRotation;
|
||||
|
||||
// --- Фаза 2: Удержание перед камерой ---
|
||||
yield return new WaitForSeconds(holdDuration);
|
||||
|
||||
// --- Фаза 3: Возвращение на место ---
|
||||
Vector3 currentPos = transform.position;
|
||||
Quaternion currentRot = transform.rotation;
|
||||
journey = 0f;
|
||||
while (journey < 1f)
|
||||
{
|
||||
journey += Time.deltaTime * animationSpeed;
|
||||
transform.position = Vector3.Lerp(currentPos, _originalPosition, journey);
|
||||
transform.rotation = Quaternion.Slerp(currentRot, _originalRotation, journey);
|
||||
yield return null;
|
||||
}
|
||||
|
||||
// --- Фаза 4: Восстановление состояния ---
|
||||
transform.position = _originalPosition;
|
||||
transform.rotation = _originalRotation;
|
||||
transform.SetParent(_originalParent);
|
||||
|
||||
_playerController.inputLocked = false;
|
||||
_isInspecting = false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9ae99608793379b5293ca0c060ccc8e8
|
||||
@@ -0,0 +1,22 @@
|
||||
using UnityEngine;
|
||||
|
||||
public class InteractableItem : MonoBehaviour, IInteractable
|
||||
{
|
||||
public ItemData itemData;
|
||||
|
||||
|
||||
public void Interact()
|
||||
{
|
||||
bool added = InventorySystem.Instance.AddItem(itemData);
|
||||
|
||||
if (added)
|
||||
{
|
||||
Destroy(gameObject);
|
||||
}
|
||||
}
|
||||
|
||||
public string GetDescription()
|
||||
{
|
||||
return $"Подобрать {itemData.itemName}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9e9df40917ad43ad841ff5580fe8ae00
|
||||
timeCreated: 1763897970
|
||||
@@ -0,0 +1,27 @@
|
||||
using UnityEngine;
|
||||
|
||||
public class InteractionHandler : MonoBehaviour
|
||||
{
|
||||
public static InteractionHandler Instance { get; private set; }
|
||||
|
||||
public delegate void OnObjectInteracted(GameObject interactedObject);
|
||||
public event OnObjectInteracted onObjectInteracted;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
if (Instance == null)
|
||||
{
|
||||
Instance = this;
|
||||
DontDestroyOnLoad(gameObject);
|
||||
}
|
||||
else
|
||||
{
|
||||
Destroy(gameObject);
|
||||
}
|
||||
}
|
||||
|
||||
public void NotifyInteraction(GameObject interactedObject)
|
||||
{
|
||||
onObjectInteracted?.Invoke(interactedObject);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d6686ae573ca461192bd0447bbec3f55
|
||||
timeCreated: 1764503264
|
||||
@@ -0,0 +1,133 @@
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
|
||||
public class InventorySystem : MonoBehaviour
|
||||
{
|
||||
public static InventorySystem Instance;
|
||||
|
||||
[Header("UI Settings")]
|
||||
public Image[] slotImages;
|
||||
public Sprite defaultEmptyIcon;
|
||||
public CanvasGroup uiCanvasGroup;
|
||||
|
||||
[Header("Settings")]
|
||||
public float fadeTime = 3f;
|
||||
|
||||
private ItemData[] _items = new ItemData[5];
|
||||
private float _timer;
|
||||
private bool _isVisible;
|
||||
public bool isInputActive = false;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
Instance = this;
|
||||
}
|
||||
|
||||
private void Start()
|
||||
{
|
||||
uiCanvasGroup.alpha = 0;
|
||||
UpdateUI();
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (!isInputActive) return;
|
||||
|
||||
HandleInput();
|
||||
HandleFade();
|
||||
}
|
||||
|
||||
private void HandleInput()
|
||||
{
|
||||
if (Input.GetKeyDown(KeyCode.Alpha1)) ShowInventory();
|
||||
if (Input.GetKeyDown(KeyCode.Alpha2)) ShowInventory();
|
||||
if (Input.GetKeyDown(KeyCode.Alpha3)) ShowInventory();
|
||||
if (Input.GetKeyDown(KeyCode.Alpha4)) ShowInventory();
|
||||
if (Input.GetKeyDown(KeyCode.Alpha5)) ShowInventory();
|
||||
}
|
||||
|
||||
private void HandleFade()
|
||||
{
|
||||
if (_timer > 0)
|
||||
{
|
||||
_timer -= Time.deltaTime;
|
||||
uiCanvasGroup.alpha = Mathf.Lerp(uiCanvasGroup.alpha, 1, Time.deltaTime * 10);
|
||||
}
|
||||
else
|
||||
{
|
||||
uiCanvasGroup.alpha = Mathf.Lerp(uiCanvasGroup.alpha, 0, Time.deltaTime * 2);
|
||||
}
|
||||
}
|
||||
|
||||
public void ShowInventory()
|
||||
{
|
||||
_timer = fadeTime;
|
||||
}
|
||||
|
||||
public bool AddItem(ItemData newItem)
|
||||
{
|
||||
if (HasItem(newItem))
|
||||
{
|
||||
Debug.Log("An item of this type is already in the inventory: " + newItem.itemName);
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int i = 0; i < _items.Length; i++)
|
||||
{
|
||||
if (_items[i] == null)
|
||||
{
|
||||
_items[i] = newItem;
|
||||
UpdateUI();
|
||||
ShowInventory();
|
||||
Debug.Log("Picked up: " + newItem.itemName);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
Debug.Log("Inventory is full!");
|
||||
return false;
|
||||
}
|
||||
|
||||
public void RemoveItem(ItemData itemToRemove)
|
||||
{
|
||||
for (int i = 0; i < _items.Length; i++)
|
||||
{
|
||||
if (_items[i] == itemToRemove)
|
||||
{
|
||||
_items[i] = null;
|
||||
UpdateUI();
|
||||
ShowInventory();
|
||||
Debug.Log("Removed: " + itemToRemove.itemName);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateUI()
|
||||
{
|
||||
for (int i = 0; i < slotImages.Length; i++)
|
||||
{
|
||||
if (_items[i] != null)
|
||||
{
|
||||
slotImages[i].sprite = _items[i].icon;
|
||||
slotImages[i].color = Color.white;
|
||||
}
|
||||
else
|
||||
{
|
||||
slotImages[i].color = Color.clear;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public bool HasItem(ItemData itemToCheck)
|
||||
{
|
||||
foreach (var item in _items)
|
||||
{
|
||||
if (item != null && item == itemToCheck)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 79dd0c393fd8d81d88040e942ed5856a
|
||||
@@ -0,0 +1,9 @@
|
||||
using UnityEngine;
|
||||
|
||||
[CreateAssetMenu(fileName = "New Item", menuName = "Inventory/Item")]
|
||||
public class ItemData : ScriptableObject
|
||||
{
|
||||
public string itemName;
|
||||
public Sprite icon; // Картинка для инвентаря
|
||||
public GameObject prefab; // (На будущее) Ссылка на модель, если будем выбрасывать
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5e3f616f6bd2990e8a22806378f28c65
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 15faa177ea0f464dbe91c46181d688a5
|
||||
timeCreated: 1764606050
|
||||
@@ -0,0 +1,18 @@
|
||||
using UnityEngine;
|
||||
|
||||
[RequireComponent(typeof(Collider))]
|
||||
public class CreakSoundTrigger : MonoBehaviour
|
||||
{
|
||||
[Tooltip("Звук скрипа, который будет проигран")]
|
||||
[SerializeField] private AudioClip creakSound;
|
||||
public AudioClip CreakSound => creakSound;
|
||||
|
||||
private void OnValidate()
|
||||
{
|
||||
var col = GetComponent<Collider>();
|
||||
if (col != null && !col.isTrigger)
|
||||
{
|
||||
col.isTrigger = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b80c4c36f608470fa13c140f779badb3
|
||||
timeCreated: 1764861764
|
||||
@@ -0,0 +1,346 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Audio;
|
||||
|
||||
namespace Player
|
||||
{
|
||||
[RequireComponent(typeof(CharacterController))]
|
||||
public class PlayerController : MonoBehaviour
|
||||
{
|
||||
[Header("Movement Settings")]
|
||||
[SerializeField] private float walkSpeed = 5f;
|
||||
[SerializeField] private float crouchSpeed = 2.5f;
|
||||
[SerializeField] private float gravity = -9.81f;
|
||||
|
||||
[Header("Look Settings")]
|
||||
public float mouseSensitivity = 2f;
|
||||
[SerializeField] private float lookXLimit = 80f;
|
||||
|
||||
[Header("Crouch Settings")]
|
||||
[SerializeField] private float crouchHeight = 1f;
|
||||
[SerializeField] private float standHeight = 1.8f;
|
||||
[SerializeField] private float crouchTransitionSpeed = 10f;
|
||||
[SerializeField] Transform cameraRoot;
|
||||
|
||||
[Header("Lean Settings (Q/E)")]
|
||||
[SerializeField] private float leanAngle = 15f;
|
||||
[SerializeField] private float leanOffset = 0.5f;
|
||||
[SerializeField] private float leanSpeed = 5f;
|
||||
|
||||
[HideInInspector]
|
||||
public bool inputLocked = false;
|
||||
|
||||
[Header("Audio Settings")]
|
||||
[SerializeField] private AudioSource footstepSource;
|
||||
|
||||
[Tooltip("Расстояние между шагами при ходьбе (в метрах)")]
|
||||
[SerializeField] private float walkStepDistance = 2.0f;
|
||||
|
||||
[Tooltip("Расстояние между шагами при присяде (в метрах)")]
|
||||
[SerializeField] private float crouchStepDistance = 1.5f;
|
||||
[SerializeField] private AudioMixerGroup footstepMixerGroup; // NEW: Reference to the mixer group
|
||||
[SerializeField] private float walkStepInterval = 0.5f;
|
||||
[SerializeField] private float crouchStepInterval = 0.8f;
|
||||
|
||||
[System.Serializable]
|
||||
public struct SurfaceLayer
|
||||
{
|
||||
public string surfaceName;
|
||||
public AudioClip footstepSound;
|
||||
}
|
||||
|
||||
[SerializeField] private List<SurfaceLayer> surfaceLayers;
|
||||
[SerializeField] private AudioClip defaultSound;
|
||||
|
||||
private float _distanceCovered;
|
||||
private CharacterController _characterController;
|
||||
private Vector3 _velocity;
|
||||
private Vector2 _rotation = Vector2.zero;
|
||||
private float _currentHeight;
|
||||
private Vector3 _lastPosition;
|
||||
|
||||
// Стейты
|
||||
private bool _isCrouching;
|
||||
|
||||
|
||||
// Ссылка на активный триггер скрипа
|
||||
private CreakSoundTrigger _activeCreakTrigger;
|
||||
private float _currentLean;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
_characterController = GetComponent<CharacterController>();
|
||||
|
||||
if (footstepSource == null)
|
||||
footstepSource = GetComponent<AudioSource>();
|
||||
|
||||
// NEW: Assign the mixer group to the AudioSource
|
||||
if (footstepSource != null && footstepMixerGroup != null)
|
||||
{
|
||||
footstepSource.outputAudioMixerGroup = footstepMixerGroup;
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogError("Footstep AudioSource or MixerGroup is not assigned!", this);
|
||||
}
|
||||
}
|
||||
|
||||
void Start()
|
||||
{
|
||||
_characterController = GetComponent<CharacterController>();
|
||||
_currentHeight = standHeight;
|
||||
_lastPosition = transform.position;
|
||||
|
||||
// Скрываем курсор
|
||||
Cursor.lockState = CursorLockMode.Locked;
|
||||
Cursor.visible = false;
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
if (inputLocked)
|
||||
{
|
||||
HandleLean(true);
|
||||
return;
|
||||
}
|
||||
|
||||
HandleMovement();
|
||||
HandleMouseLook();
|
||||
HandleCrouch();
|
||||
HandleLean(false);
|
||||
HandleFootsteps();
|
||||
}
|
||||
|
||||
private void HandleMovement()
|
||||
{
|
||||
// Определяем, на земле ли мы
|
||||
bool isGrounded = _characterController.isGrounded;
|
||||
if (isGrounded && _velocity.y < 0)
|
||||
{
|
||||
_velocity.y = -2f;
|
||||
}
|
||||
|
||||
// Ввод WASD
|
||||
float moveX = Input.GetAxis("Horizontal");
|
||||
float moveZ = Input.GetAxis("Vertical");
|
||||
|
||||
// Выбор скорости (идем или крадемся)
|
||||
float speed = _isCrouching ? crouchSpeed : walkSpeed;
|
||||
|
||||
// Вектор движения относительно направления взгляда
|
||||
Vector3 move = transform.right * moveX + transform.forward * moveZ;
|
||||
|
||||
// Применяем движение
|
||||
_characterController.Move(move * (speed * Time.deltaTime));
|
||||
|
||||
// Применяем гравитацию
|
||||
_velocity.y += gravity * Time.deltaTime;
|
||||
_characterController.Move(_velocity * Time.deltaTime);
|
||||
}
|
||||
|
||||
private void HandleMouseLook()
|
||||
{
|
||||
_rotation.y += Input.GetAxis("Mouse X") * mouseSensitivity;
|
||||
_rotation.x += -Input.GetAxis("Mouse Y") * mouseSensitivity;
|
||||
|
||||
// Ограничение взгляда вверх/вниз
|
||||
_rotation.x = Mathf.Clamp(_rotation.x, -lookXLimit, lookXLimit);
|
||||
|
||||
// Вращаем тело персонажа по Y (влево-вправо)
|
||||
transform.localRotation = Quaternion.Euler(0, _rotation.y, 0);
|
||||
|
||||
// Вращаем камеру по X (вверх-вниз).
|
||||
// ВАЖНО: Вращаем CameraRoot, а не саму камеру, чтобы не ломать наклоны
|
||||
cameraRoot.localRotation = Quaternion.Euler(_rotation.x, 0, 0);
|
||||
}
|
||||
|
||||
private void HandleCrouch()
|
||||
{
|
||||
// Левый Ctrl
|
||||
if (Input.GetKeyDown(KeyCode.LeftControl)) _isCrouching = true;
|
||||
if (Input.GetKeyUp(KeyCode.LeftControl)) _isCrouching = false;
|
||||
|
||||
// Вычисляем целевую высоту
|
||||
float targetHeight = _isCrouching ? crouchHeight : standHeight;
|
||||
|
||||
// Плавное изменение высоты контроллера (чтобы не проваливаться сквозь пол, меняем center)
|
||||
// Но проще менять высоту контроллера и позицию камеры
|
||||
_currentHeight = Mathf.Lerp(_currentHeight, targetHeight, Time.deltaTime * crouchTransitionSpeed);
|
||||
_characterController.height = _currentHeight;
|
||||
|
||||
// Корректируем центр контроллера, чтобы ноги оставались на земле
|
||||
_characterController.center = new Vector3(0, _currentHeight / 2, 0);
|
||||
|
||||
// Корректируем высоту камеры (глаз)
|
||||
// Когда стоим - камера высоко, когда сидим - ниже.
|
||||
// Предполагаем, что глаза находятся чуть ниже макушки
|
||||
float targetCamY = _currentHeight - 0.2f;
|
||||
Vector3 camPos = cameraRoot.localPosition;
|
||||
camPos.y = targetCamY;
|
||||
|
||||
// Тут интерполяцию можно не делать, так как height интерполируется выше, но для подстраховки:
|
||||
cameraRoot.localPosition = camPos;
|
||||
}
|
||||
|
||||
private void HandleLean(bool forceReset)
|
||||
{
|
||||
float targetLean = 0f;
|
||||
|
||||
if (!forceReset)
|
||||
{
|
||||
if (Input.GetKey(KeyCode.Q)) targetLean = 1f;
|
||||
else if (Input.GetKey(KeyCode.E)) targetLean = -1f;
|
||||
}
|
||||
|
||||
// Плавный переход к цели
|
||||
_currentLean = Mathf.MoveTowards(_currentLean, targetLean, leanSpeed * Time.deltaTime);
|
||||
Quaternion lookRotation = Quaternion.Euler(_rotation.x, 0, 0);
|
||||
Quaternion leanRotation = Quaternion.Euler(0, 0, _currentLean * leanAngle);
|
||||
cameraRoot.localRotation = lookRotation * leanRotation;
|
||||
|
||||
// Рассчитываем наклон и смещение
|
||||
// Вращение по Z (Roll)
|
||||
// Нам нужно применить наклон поверх взгляда вверх-вниз.
|
||||
// Мы знаем, что в HandleMouseLook мы задаем (rotation.x, 0, 0).
|
||||
// Добавим к этому Z поворот.
|
||||
cameraRoot.localRotation = Quaternion.Euler(_rotation.x, 0, _currentLean * leanAngle);
|
||||
|
||||
// Смещение позиции (чтобы голова реально сдвигалась, а не просто крутилась)
|
||||
// Сдвигаем дочернюю камеру, а не рут, или сам рут локально
|
||||
// Лучше сдвигать CameraRoot локально по X
|
||||
Vector3 currentPos = cameraRoot.localPosition;
|
||||
float targetX = -_currentLean * leanOffset;
|
||||
currentPos.x = targetX;
|
||||
cameraRoot.localPosition = currentPos;
|
||||
}
|
||||
|
||||
private void HandleFootsteps()
|
||||
{
|
||||
if (!_characterController.isGrounded) return;
|
||||
|
||||
// перемещение по горизонтали
|
||||
Vector3 currentPosFlat = new Vector3(transform.position.x, 0, transform.position.z);
|
||||
Vector3 lastPosFlat = new Vector3(_lastPosition.x, 0, _lastPosition.z);
|
||||
float distanceMoved = Vector3.Distance(currentPosFlat, lastPosFlat);
|
||||
|
||||
_lastPosition = transform.position;
|
||||
|
||||
// Если мы вообще двигались, добавляем пройденное расстояние к счетчику
|
||||
if (distanceMoved > 0)
|
||||
{
|
||||
_distanceCovered += distanceMoved;
|
||||
}
|
||||
|
||||
float currentInterval = _isCrouching ? crouchStepInterval : walkStepInterval;
|
||||
var _stepTimer = Time.deltaTime;
|
||||
// Определяем, какое расстояние нужно пройти для следующего шага
|
||||
float stepDistance = _isCrouching ? crouchStepDistance : walkStepDistance;
|
||||
|
||||
// Если накопленное расстояние превышает дистанцию шага
|
||||
if (_distanceCovered >= stepDistance)
|
||||
{
|
||||
PlayFootstepSound();
|
||||
_distanceCovered -= stepDistance; // Вычитаем дистанцию шага, а не сбрасываем в 0
|
||||
}
|
||||
}
|
||||
|
||||
private void PlayFootstepSound()
|
||||
{
|
||||
if (_activeCreakTrigger != null && _activeCreakTrigger.CreakSound != null)
|
||||
{
|
||||
PlaySound(_activeCreakTrigger.CreakSound);
|
||||
return; // Выходим, чтобы не проигрывать обычный звук шага
|
||||
}
|
||||
|
||||
RaycastHit hit;
|
||||
|
||||
if (Physics.Raycast(transform.position + Vector3.up * 0.5f, Vector3.down, out hit, 2.0f))
|
||||
{
|
||||
string keyName = "";
|
||||
|
||||
Terrain terrain = hit.collider.GetComponent<Terrain>();
|
||||
if (terrain != null)
|
||||
{
|
||||
keyName = GetDominantTextureName(transform.position, terrain);
|
||||
}
|
||||
else
|
||||
{
|
||||
keyName = hit.collider.tag;
|
||||
}
|
||||
|
||||
// Ищем звук
|
||||
SurfaceLayer foundLayer = surfaceLayers.Find(layer => layer.surfaceName == keyName);
|
||||
|
||||
if (foundLayer.footstepSound != null)
|
||||
{
|
||||
PlaySound(foundLayer.footstepSound);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (defaultSound != null) PlaySound(defaultSound);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private string GetDominantTextureName(Vector3 playerPos, Terrain terrain)
|
||||
{
|
||||
TerrainData terrainData = terrain.terrainData;
|
||||
Vector3 terrainPos = terrain.transform.position;
|
||||
|
||||
// 1. Переводим координаты игрока в координаты карты текстур (Alphamap)
|
||||
int mapX = (int)(((playerPos.x - terrainPos.x) / terrainData.size.x) * terrainData.alphamapWidth);
|
||||
int mapZ = (int)(((playerPos.z - terrainPos.z) / terrainData.size.z) * terrainData.alphamapHeight);
|
||||
|
||||
// 2. Получаем смешивание текстур в этой точке (3-мерный массив [z, x, layer])
|
||||
float[,,] splatmapData = terrainData.GetAlphamaps(mapX, mapZ, 1, 1);
|
||||
|
||||
// 3. Ищем индекс самой "сильной" текстуры
|
||||
float maxMix = 0;
|
||||
int maxIndex = 0;
|
||||
|
||||
// Проходимся по всем слоям текстур
|
||||
for (int i = 0; i < terrainData.alphamapLayers; i++)
|
||||
{
|
||||
if (splatmapData[0, 0, i] > maxMix)
|
||||
{
|
||||
maxMix = splatmapData[0, 0, i];
|
||||
maxIndex = i;
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Возвращаем имя слоя (Terrain Layer Name)
|
||||
return terrainData.terrainLayers[maxIndex].name;
|
||||
}
|
||||
|
||||
private void PlaySound(AudioClip clip)
|
||||
{
|
||||
if (clip == null) return;
|
||||
|
||||
footstepSource.pitch = Random.Range(0.95f, 1.05f);
|
||||
footstepSource.volume = Random.Range(0.9f, 1.0f);
|
||||
|
||||
footstepSource.PlayOneShot(clip);
|
||||
}
|
||||
|
||||
private void OnTriggerEnter(Collider other)
|
||||
{
|
||||
if (other.TryGetComponent<CreakSoundTrigger>(out var creakTrigger))
|
||||
{
|
||||
_activeCreakTrigger = creakTrigger;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnTriggerExit(Collider other)
|
||||
{
|
||||
if (other.TryGetComponent<CreakSoundTrigger>(out var creakTrigger) && _activeCreakTrigger == creakTrigger)
|
||||
{
|
||||
_activeCreakTrigger = null;
|
||||
}
|
||||
}
|
||||
|
||||
public void PlayOneShotSound(AudioClip clip)
|
||||
{
|
||||
if (clip != null) footstepSource.PlayOneShot(clip);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f41650f7781f12b8da7439f0a78e3be6
|
||||
@@ -0,0 +1,145 @@
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
|
||||
public class PlayerHandsController : MonoBehaviour
|
||||
{
|
||||
public static PlayerHandsController Instance;
|
||||
|
||||
[Header("Visual Models")]
|
||||
public GameObject emptyBagModel;
|
||||
public GameObject fullBagModel;
|
||||
|
||||
[Header("Broom Settings")]
|
||||
[SerializeField] private GameObject broomModel;
|
||||
[SerializeField] private float sweepAnimationDuration = 1.5f;
|
||||
[SerializeField] private float sweepAngle = 30f;
|
||||
|
||||
[Header("Rag Settings")]
|
||||
[SerializeField] private GameObject ragModel; // Model for the rag in hand
|
||||
[SerializeField] private float wipeAnimationDuration = 1.0f;
|
||||
[SerializeField] private float wipeDistance = 0.1f;
|
||||
|
||||
private Coroutine _animationCoroutine;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
Instance = this;
|
||||
}
|
||||
|
||||
private void Start()
|
||||
{
|
||||
HideHands(); // Hides all models at the start
|
||||
}
|
||||
|
||||
public void ShowBag(bool isFull)
|
||||
{
|
||||
HideHands();
|
||||
if (emptyBagModel) emptyBagModel.SetActive(!isFull);
|
||||
if (fullBagModel) fullBagModel.SetActive(isFull);
|
||||
}
|
||||
|
||||
public void ShowBroom(bool state)
|
||||
{
|
||||
HideHands();
|
||||
if (broomModel != null)
|
||||
{
|
||||
broomModel.SetActive(state);
|
||||
}
|
||||
}
|
||||
|
||||
public void ShowRag(bool state)
|
||||
{
|
||||
HideHands();
|
||||
if (ragModel != null)
|
||||
{
|
||||
ragModel.SetActive(state);
|
||||
}
|
||||
}
|
||||
|
||||
public void HideHands()
|
||||
{
|
||||
if (emptyBagModel) emptyBagModel.SetActive(false);
|
||||
if (fullBagModel) fullBagModel.SetActive(false);
|
||||
if (broomModel) broomModel.SetActive(false);
|
||||
if (ragModel) ragModel.SetActive(false);
|
||||
}
|
||||
|
||||
public void PlaySweepAnimation()
|
||||
{
|
||||
if (broomModel != null && broomModel.activeInHierarchy)
|
||||
{
|
||||
if (_animationCoroutine != null) StopCoroutine(_animationCoroutine);
|
||||
_animationCoroutine = StartCoroutine(SweepRoutine());
|
||||
}
|
||||
}
|
||||
|
||||
public void PlayWipeAnimation()
|
||||
{
|
||||
if (ragModel != null && ragModel.activeInHierarchy)
|
||||
{
|
||||
if (_animationCoroutine != null) StopCoroutine(_animationCoroutine);
|
||||
_animationCoroutine = StartCoroutine(WipeRoutine());
|
||||
}
|
||||
}
|
||||
|
||||
private IEnumerator SweepRoutine()
|
||||
{
|
||||
Quaternion startRotation = broomModel.transform.localRotation;
|
||||
Quaternion forwardRotation = startRotation * Quaternion.Euler(sweepAngle, 0, 0);
|
||||
Quaternion backwardRotation = startRotation * Quaternion.Euler(-sweepAngle / 2, 0, 0);
|
||||
float halfDuration = sweepAnimationDuration / 2;
|
||||
float timer = 0f;
|
||||
|
||||
while (timer < halfDuration)
|
||||
{
|
||||
timer += Time.deltaTime;
|
||||
broomModel.transform.localRotation = Quaternion.Slerp(startRotation, forwardRotation, timer / halfDuration);
|
||||
yield return null;
|
||||
}
|
||||
timer = 0f;
|
||||
while (timer < halfDuration)
|
||||
{
|
||||
timer += Time.deltaTime;
|
||||
broomModel.transform.localRotation = Quaternion.Slerp(forwardRotation, backwardRotation, timer / halfDuration);
|
||||
yield return null;
|
||||
}
|
||||
broomModel.transform.localRotation = startRotation;
|
||||
_animationCoroutine = null;
|
||||
}
|
||||
|
||||
private IEnumerator WipeRoutine()
|
||||
{
|
||||
Vector3 startPosition = ragModel.transform.localPosition;
|
||||
Vector3 forwardPosition = startPosition + new Vector3(wipeDistance, 0, 0);
|
||||
Vector3 backwardPosition = startPosition - new Vector3(wipeDistance, 0, 0);
|
||||
float quarterDuration = wipeAnimationDuration / 4;
|
||||
float timer = 0f;
|
||||
|
||||
// Wipe forward
|
||||
while (timer < quarterDuration)
|
||||
{
|
||||
timer += Time.deltaTime;
|
||||
ragModel.transform.localPosition = Vector3.Lerp(startPosition, forwardPosition, timer / quarterDuration);
|
||||
yield return null;
|
||||
}
|
||||
// Wipe back
|
||||
timer = 0f;
|
||||
while (timer < quarterDuration * 2)
|
||||
{
|
||||
timer += Time.deltaTime;
|
||||
ragModel.transform.localPosition = Vector3.Lerp(forwardPosition, backwardPosition, timer / (quarterDuration * 2));
|
||||
yield return null;
|
||||
}
|
||||
// Return to start
|
||||
timer = 0f;
|
||||
while (timer < quarterDuration)
|
||||
{
|
||||
timer += Time.deltaTime;
|
||||
ragModel.transform.localPosition = Vector3.Lerp(backwardPosition, startPosition, timer / quarterDuration);
|
||||
yield return null;
|
||||
}
|
||||
|
||||
ragModel.transform.localPosition = startPosition;
|
||||
_animationCoroutine = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 174fee868b4d450ab43b014ba2fcfe46
|
||||
timeCreated: 1764526106
|
||||
@@ -0,0 +1,86 @@
|
||||
using UnityEngine;
|
||||
|
||||
public class PlayerInteraction : MonoBehaviour
|
||||
{
|
||||
public float interactionDistance = 3f;
|
||||
public LayerMask interactionLayer;
|
||||
|
||||
private Outline previousOutline = null;
|
||||
private GameObject currentInteractableObject = null;
|
||||
|
||||
void Update()
|
||||
{
|
||||
Ray ray = new Ray(transform.position, transform.forward);
|
||||
RaycastHit hit;
|
||||
|
||||
// Сбрасываем текущие найденные объекты в начале каждого кадра
|
||||
IInteractable interactable = null;
|
||||
currentInteractableObject = null;
|
||||
Outline currentOutline = null;
|
||||
|
||||
if (Physics.Raycast(ray, out hit, interactionDistance, interactionLayer))
|
||||
{
|
||||
Transform currentTransform = hit.collider.transform;
|
||||
|
||||
// Ищем IInteractable, поднимаясь по иерархии
|
||||
while (currentTransform != null)
|
||||
{
|
||||
IInteractable potentialInteractable = currentTransform.GetComponent<IInteractable>();
|
||||
if (potentialInteractable != null)
|
||||
{
|
||||
// *** ГЛАВНОЕ ИЗМЕНЕНИЕ ***
|
||||
// Проверяем, есть ли у объекта описание в данный момент.
|
||||
// Если описание пустое, значит, объект неактивен.
|
||||
if (!string.IsNullOrEmpty(potentialInteractable.GetDescription()))
|
||||
{
|
||||
interactable = potentialInteractable;
|
||||
currentInteractableObject = currentTransform.gameObject;
|
||||
currentOutline = currentTransform.GetComponent<Outline>();
|
||||
break; // Нашли валидный интерактивный объект, выходим из цикла
|
||||
}
|
||||
}
|
||||
currentTransform = currentTransform.parent;
|
||||
}
|
||||
}
|
||||
|
||||
// Логика выключения подсветки для предыдущего объекта
|
||||
if (previousOutline != null && previousOutline != currentOutline)
|
||||
{
|
||||
previousOutline.enabled = false;
|
||||
}
|
||||
|
||||
// Если мы нашли валидный интерактивный объект (с описанием)
|
||||
if (interactable != null)
|
||||
{
|
||||
// Включаем подсветку
|
||||
if (currentOutline != null)
|
||||
{
|
||||
currentOutline.enabled = true;
|
||||
previousOutline = currentOutline;
|
||||
}
|
||||
|
||||
// Обрабатываем нажатие клавиши
|
||||
if (Input.GetKeyDown(KeyCode.F))
|
||||
{
|
||||
interactable.Interact();
|
||||
|
||||
// После взаимодействия подсветка должна сразу пропасть,
|
||||
// поэтому сбрасываем ее здесь, не дожидаясь следующего кадра.
|
||||
if (currentOutline != null)
|
||||
{
|
||||
currentOutline.enabled = false;
|
||||
}
|
||||
previousOutline = null;
|
||||
}
|
||||
}
|
||||
else // Если не нашли ничего интерактивного
|
||||
{
|
||||
// Убеждаемся, что старая подсветка выключена
|
||||
if (previousOutline != null)
|
||||
{
|
||||
previousOutline.enabled = false;
|
||||
previousOutline = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 63dc043b60bb4b37a02bb281afd76b88
|
||||
timeCreated: 1763898046
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2793ca3fa9474154ba4ad55bfb8bd501
|
||||
timeCreated: 1764606129
|
||||
@@ -0,0 +1,103 @@
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// A generic component for objects that can be "cleaned" or "removed"
|
||||
/// by fading them out. Requires a specific item in the inventory.
|
||||
/// </summary>
|
||||
public class FadableObject : MonoBehaviour, IInteractable
|
||||
{
|
||||
[Header("Settings")]
|
||||
[Tooltip("The item required in the inventory to interact with this object.")]
|
||||
[SerializeField] private ItemData requiredItem;
|
||||
[Tooltip("How long it takes for the object to fade out completely.")]
|
||||
[SerializeField] private float fadeDuration = 1.5f;
|
||||
|
||||
private bool isFading = false;
|
||||
private Renderer _renderer;
|
||||
|
||||
private void Start()
|
||||
{
|
||||
_renderer = GetComponent<Renderer>();
|
||||
if (_renderer == null)
|
||||
{
|
||||
_renderer = GetComponentInChildren<Renderer>();
|
||||
}
|
||||
if (requiredItem == null)
|
||||
{
|
||||
Debug.LogError($"FadableObject on '{gameObject.name}' is missing a 'requiredItem'.", this);
|
||||
}
|
||||
}
|
||||
|
||||
public void Interact()
|
||||
{
|
||||
if (isFading) return;
|
||||
|
||||
// Check if the player has the required item
|
||||
if (InventorySystem.Instance.HasItem(requiredItem))
|
||||
{
|
||||
// We don't check for a specific quest here.
|
||||
// We just notify the InteractionHandler, and the active quest will decide if it's relevant.
|
||||
StartCoroutine(FadeOutRoutine());
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Log($"A '{requiredItem?.itemName}' is needed to clean this!");
|
||||
}
|
||||
}
|
||||
|
||||
private IEnumerator FadeOutRoutine()
|
||||
{
|
||||
isFading = true;
|
||||
|
||||
// Notify the quest system that an interaction happened.
|
||||
InteractionHandler.Instance.NotifyInteraction(gameObject);
|
||||
|
||||
// Trigger the appropriate animation based on the required item.
|
||||
// This is a simple but effective way to manage different tool animations.
|
||||
if (requiredItem.itemName.ToLower().Contains("broom"))
|
||||
{
|
||||
PlayerHandsController.Instance?.PlaySweepAnimation();
|
||||
}
|
||||
else if (requiredItem.itemName.ToLower().Contains("rag"))
|
||||
{
|
||||
PlayerHandsController.Instance?.PlayWipeAnimation();
|
||||
}
|
||||
|
||||
// Fade-out logic
|
||||
if (_renderer != null)
|
||||
{
|
||||
Material mat = _renderer.material;
|
||||
Color startColor = mat.color;
|
||||
float timer = 0f;
|
||||
|
||||
while (timer < fadeDuration)
|
||||
{
|
||||
timer += Time.deltaTime;
|
||||
float alpha = Mathf.Lerp(startColor.a, 0f, timer / fadeDuration);
|
||||
mat.color = new Color(startColor.r, startColor.g, startColor.b, alpha);
|
||||
yield return null;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
yield return new WaitForSeconds(fadeDuration);
|
||||
}
|
||||
|
||||
Debug.Log($"Object '{gameObject.name}' faded out and destroyed.");
|
||||
Destroy(gameObject);
|
||||
}
|
||||
|
||||
public string GetDescription()
|
||||
{
|
||||
if (isFading) return "";
|
||||
|
||||
// Provide a dynamic description
|
||||
if (requiredItem != null)
|
||||
{
|
||||
if (requiredItem.itemName.ToLower().Contains("broom")) return "Sweep";
|
||||
if (requiredItem.itemName.ToLower().Contains("rag")) return "Wipe";
|
||||
}
|
||||
return "Clean";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 1619763fbc3892a769f87a37f1883a79
|
||||
@@ -0,0 +1,16 @@
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
|
||||
public interface IQuest
|
||||
{
|
||||
string QuestName { get; }
|
||||
string Description { get; }
|
||||
int CurrentStep { get; }
|
||||
int TotalSteps { get; }
|
||||
bool IsCompleted { get; }
|
||||
event System.Action<string>
|
||||
OnQuestStepChanged;
|
||||
void StartQuest();
|
||||
void CompleteQuest();
|
||||
void AdvanceQuestStep();
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e856f540eff0ff3ca992f9150b0bb6b3
|
||||
@@ -0,0 +1,34 @@
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// A simple component that makes an object interactable
|
||||
/// and just notifies the InteractionHandler that it has been interacted with.
|
||||
/// Ideal for objects that don't have complex logic but need to be recognized
|
||||
/// by the quest system (e.g., a dumpster).
|
||||
/// </summary>
|
||||
public class NotifyInteractionObject : MonoBehaviour, IInteractable
|
||||
{
|
||||
[SerializeField]
|
||||
private string description = "Interact";
|
||||
|
||||
public void Interact()
|
||||
{
|
||||
// Check if InteractionHandler exists
|
||||
if (InteractionHandler.Instance != null)
|
||||
{
|
||||
// Notify the system that this object (gameObject) has been interacted with.
|
||||
// The QuestManager, subscribed to this event, will receive the notification.
|
||||
InteractionHandler.Instance.NotifyInteraction(gameObject);
|
||||
Debug.Log($"Interaction notified for {gameObject.name}");
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogError("InteractionHandler.Instance is not found in the scene.");
|
||||
}
|
||||
}
|
||||
|
||||
public string GetDescription()
|
||||
{
|
||||
return description;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 661e0d1c241c4ed0ab7688ebb0292308
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3751add09ea346e99574f83336b33773
|
||||
timeCreated: 1764607784
|
||||
@@ -0,0 +1,30 @@
|
||||
using UnityEngine;
|
||||
|
||||
public class PickupBagAction : MonoBehaviour, IInteractable
|
||||
{
|
||||
[Header("Settings")]
|
||||
public ItemData bagItemData; // Reference to the bag's ScriptableObject
|
||||
|
||||
public void Interact()
|
||||
{
|
||||
// 1. Try to add the item to the inventory
|
||||
bool added = InventorySystem.Instance.AddItem(bagItemData);
|
||||
|
||||
if (added)
|
||||
{
|
||||
// 2. Notify the quest system that we interacted with this object
|
||||
// The quest itself will decide what to do next (e.g., show the bag in hand)
|
||||
if (InteractionHandler.Instance != null)
|
||||
{
|
||||
InteractionHandler.Instance.NotifyInteraction(gameObject);
|
||||
}
|
||||
}
|
||||
// If the item was not added (already exists or no space), do nothing.
|
||||
// A message about this is logged from the InventorySystem.
|
||||
}
|
||||
|
||||
public string GetDescription()
|
||||
{
|
||||
return "Pick up trash bags";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: eae795e938db451ebcd0e939e9f3366b
|
||||
timeCreated: 1764526904
|
||||
@@ -0,0 +1,16 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace Quest_Environment.Q1
|
||||
{
|
||||
public class TrashBin :MonoBehaviour,IInteractable
|
||||
{
|
||||
public void Interact()
|
||||
{
|
||||
|
||||
}
|
||||
public string GetDescription()
|
||||
{
|
||||
return "Положить в мусорку";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 12f55188f40241dd84d50be74a4eb8ac
|
||||
timeCreated: 1764607809
|
||||
@@ -0,0 +1,61 @@
|
||||
using Quests;
|
||||
using UnityEngine;
|
||||
|
||||
public class TrashPile : MonoBehaviour, IInteractable
|
||||
{
|
||||
[Header("Settings")]
|
||||
public ItemData requiredBagItem; // Ссылка на ItemData мешка (для проверки в инвентаре)
|
||||
|
||||
public void Interact()
|
||||
{
|
||||
// 1. Проверяем, что сейчас активен именно квест по сбору мусора
|
||||
if (QuestManager.Instance?.currentQuest is Q1CollectGarbageQuest garbageQuest)
|
||||
{
|
||||
// 2. Проверяем, есть ли у игрока мешок
|
||||
if (InventorySystem.Instance.HasItem(requiredBagItem))
|
||||
{
|
||||
// 3. Проверяем, не полон ли мешок
|
||||
if (garbageQuest.IsBagFull())
|
||||
{
|
||||
Debug.Log("Мешок полон! Сначала выбросьте его в контейнер.");
|
||||
}
|
||||
else
|
||||
{
|
||||
// Если все проверки пройдены, уведомляем систему квестов
|
||||
InteractionHandler.Instance.NotifyInteraction(gameObject);
|
||||
// Уничтожаем объект мусора
|
||||
Destroy(gameObject);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Log("Нужен мешок для мусора!");
|
||||
}
|
||||
}
|
||||
// Если активен другой квест, ничего не делаем.
|
||||
}
|
||||
|
||||
public string GetDescription()
|
||||
{
|
||||
// Даем описание, только если активен квест по сбору мусора
|
||||
if (QuestManager.Instance?.currentQuest is Q1CollectGarbageQuest garbageQuest)
|
||||
{
|
||||
// Проверяем, есть ли у игрока мешок
|
||||
if (!InventorySystem.Instance.HasItem(requiredBagItem))
|
||||
{
|
||||
return "Нужен мешок для мусора"; // Подсказка, если нет мешка
|
||||
}
|
||||
|
||||
// Проверяем, не полон ли мешок
|
||||
if (garbageQuest.IsBagFull())
|
||||
{
|
||||
return "Мешок полон!";
|
||||
}
|
||||
|
||||
return "Собрать мусор"; // Стандартное описание
|
||||
}
|
||||
|
||||
// Если квест неактивен, возвращаем пустую строку
|
||||
return "";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3d20c394d52e426d964b8cf9d1de6b83
|
||||
timeCreated: 1764526435
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a18989bdc07f4b54b795f6e9f37fccaf
|
||||
timeCreated: 1764782534
|
||||
@@ -0,0 +1,86 @@
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Quest_Environment.Q2
|
||||
{
|
||||
public class DirtSpot : MonoBehaviour, IInteractable
|
||||
{
|
||||
[Header("Settings")]
|
||||
public ItemData requiredBroomItem;
|
||||
[SerializeField] private float cleanDuration = 1.5f;
|
||||
|
||||
private bool isCleaning = false;
|
||||
private Renderer _renderer;
|
||||
|
||||
private void Start()
|
||||
{
|
||||
_renderer = GetComponent<Renderer>();
|
||||
if (_renderer == null)
|
||||
{
|
||||
_renderer = GetComponentInChildren<Renderer>();
|
||||
}
|
||||
}
|
||||
|
||||
public void Interact()
|
||||
{
|
||||
if (isCleaning) return;
|
||||
|
||||
bool hasBroom = InventorySystem.Instance.HasItem(requiredBroomItem);
|
||||
|
||||
if (hasBroom)
|
||||
{
|
||||
if (QuestManager.Instance != null && QuestManager.Instance.currentQuest is Q2_SweepDirtQuest)
|
||||
{
|
||||
StartCoroutine(CleanRoutine());
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Log("It's dirty here, but I have no reason to clean it right now.");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Log("A broom is needed to clean this!");
|
||||
}
|
||||
}
|
||||
|
||||
private IEnumerator CleanRoutine()
|
||||
{
|
||||
isCleaning = true;
|
||||
|
||||
// --- TRIGGER ANIMATION ---
|
||||
PlayerHandsController.Instance?.PlaySweepAnimation();
|
||||
// -------------------------
|
||||
|
||||
InteractionHandler.Instance.NotifyInteraction(gameObject);
|
||||
|
||||
if (_renderer != null)
|
||||
{
|
||||
Material mat = _renderer.material;
|
||||
Color startColor = mat.color;
|
||||
float timer = 0f;
|
||||
|
||||
while (timer < cleanDuration)
|
||||
{
|
||||
timer += Time.deltaTime;
|
||||
float alpha = Mathf.Lerp(startColor.a, 0f, timer / cleanDuration);
|
||||
mat.color = new Color(startColor.r, startColor.g, startColor.b, alpha);
|
||||
yield return null;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
yield return new WaitForSeconds(cleanDuration);
|
||||
}
|
||||
|
||||
Debug.Log("Dirt cleaned!");
|
||||
Destroy(gameObject);
|
||||
}
|
||||
|
||||
public string GetDescription()
|
||||
{
|
||||
if (isCleaning) return "";
|
||||
return "Sweep";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 684169532f6d4bb586538dd24ed55a1b
|
||||
timeCreated: 1764782543
|
||||
@@ -0,0 +1,41 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace Quest_Environment.Q2
|
||||
{
|
||||
public class PickupBroomAction : MonoBehaviour, IInteractable
|
||||
{
|
||||
[Header("Settings")]
|
||||
public ItemData broomItemData;
|
||||
|
||||
public void Interact()
|
||||
{
|
||||
// Check if the current quest is the correct one for this item
|
||||
if (!(QuestManager.Instance?.currentQuest is Q2_SweepDirtQuest))
|
||||
{
|
||||
Debug.Log("I have no reason to pick this up right now.");
|
||||
return; // Do nothing if it's not the right quest
|
||||
}
|
||||
|
||||
bool added = InventorySystem.Instance.AddItem(broomItemData);
|
||||
|
||||
if (added)
|
||||
{
|
||||
if (InteractionHandler.Instance != null)
|
||||
{
|
||||
InteractionHandler.Instance.NotifyInteraction(gameObject);
|
||||
}
|
||||
Destroy(gameObject);
|
||||
}
|
||||
}
|
||||
|
||||
public string GetDescription()
|
||||
{
|
||||
// Only show the description if the correct quest is active
|
||||
if (QuestManager.Instance?.currentQuest is Q2_SweepDirtQuest)
|
||||
{
|
||||
return "Take the broom";
|
||||
}
|
||||
return ""; // Return empty string to hide the prompt
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 89b798cd1bc445fe999ee96661e67ec0
|
||||
timeCreated: 1764782752
|
||||
@@ -0,0 +1,144 @@
|
||||
using UnityEngine;
|
||||
using Player;
|
||||
|
||||
namespace Quest_Environment.Q2
|
||||
{
|
||||
public class Q2_SweepDirtQuest : MonoBehaviour, IQuest
|
||||
{
|
||||
[Header("Quest Settings")]
|
||||
[SerializeField] private string questName = "Room Cleaning";
|
||||
[SerializeField] private int dirtPilesTotal = 5;
|
||||
[SerializeField] private ItemData broomItem;
|
||||
|
||||
[Header("Target Tags")]
|
||||
[SerializeField] private string broomGiverTag = "BroomLocation";
|
||||
[SerializeField] private string dirtTag = "Dirt";
|
||||
|
||||
[Header("Audio Settings")]
|
||||
[SerializeField] private AudioClip pickupBroomSound;
|
||||
[SerializeField] private AudioClip cleanDirtSound;
|
||||
|
||||
private PlayerController _playerController;
|
||||
|
||||
private enum Stage
|
||||
{
|
||||
NotStarted,
|
||||
FindBroom,
|
||||
SweepDirt,
|
||||
Completed
|
||||
}
|
||||
|
||||
private Stage currentStage = Stage.NotStarted;
|
||||
private int cleanedDirtCount = 0;
|
||||
|
||||
public string QuestName => questName;
|
||||
public string Description { get; private set; }
|
||||
public int CurrentStep => cleanedDirtCount;
|
||||
public int TotalSteps => dirtPilesTotal;
|
||||
public bool IsCompleted => currentStage == Stage.Completed;
|
||||
|
||||
public event System.Action<string> OnQuestStepChanged;
|
||||
|
||||
public void StartQuest()
|
||||
{
|
||||
if (broomItem == null) Debug.LogError($"[Q2] Broom ItemData is missing!");
|
||||
|
||||
currentStage = Stage.FindBroom;
|
||||
cleanedDirtCount = 0;
|
||||
PlayerHandsController.Instance?.HideHands();
|
||||
|
||||
_playerController = FindObjectOfType<PlayerController>();
|
||||
|
||||
if (InteractionHandler.Instance != null)
|
||||
{
|
||||
InteractionHandler.Instance.onObjectInteracted += HandleInteraction;
|
||||
}
|
||||
UpdateQuestState();
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
if (InteractionHandler.Instance != null)
|
||||
{
|
||||
InteractionHandler.Instance.onObjectInteracted -= HandleInteraction;
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleInteraction(GameObject obj)
|
||||
{
|
||||
if (currentStage == Stage.Completed || obj == null) return;
|
||||
|
||||
switch (currentStage)
|
||||
{
|
||||
case Stage.FindBroom:
|
||||
if (obj.CompareTag(broomGiverTag))
|
||||
{
|
||||
currentStage = Stage.SweepDirt;
|
||||
_playerController?.PlayOneShotSound(pickupBroomSound);
|
||||
PlayerHandsController.Instance?.ShowBroom(true);
|
||||
UpdateQuestState();
|
||||
}
|
||||
break;
|
||||
|
||||
case Stage.SweepDirt:
|
||||
if (obj.CompareTag(dirtTag))
|
||||
{
|
||||
cleanedDirtCount++;
|
||||
_playerController?.PlayOneShotSound(cleanDirtSound);
|
||||
QuestManager.Instance.StepCompleted();
|
||||
|
||||
if (cleanedDirtCount >= dirtPilesTotal)
|
||||
{
|
||||
FinishQuest();
|
||||
}
|
||||
else
|
||||
{
|
||||
UpdateQuestState();
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateQuestState()
|
||||
{
|
||||
switch (currentStage)
|
||||
{
|
||||
case Stage.FindBroom:
|
||||
Description = "Find a broom.";
|
||||
break;
|
||||
case Stage.SweepDirt:
|
||||
Description = "Sweep the floors in the rooms.";
|
||||
break;
|
||||
case Stage.Completed:
|
||||
Description = "The floor is clean!";
|
||||
break;
|
||||
}
|
||||
OnQuestStepChanged?.Invoke(Description);
|
||||
}
|
||||
|
||||
private void FinishQuest()
|
||||
{
|
||||
currentStage = Stage.Completed;
|
||||
|
||||
// Hide the broom and remove it from inventory
|
||||
PlayerHandsController.Instance?.ShowBroom(false);
|
||||
if (broomItem != null)
|
||||
{
|
||||
InventorySystem.Instance.RemoveItem(broomItem);
|
||||
}
|
||||
|
||||
UpdateQuestState();
|
||||
QuestManager.Instance.CompleteQuest();
|
||||
}
|
||||
|
||||
public void AdvanceQuestStep() { }
|
||||
public void CompleteQuest()
|
||||
{
|
||||
if (InteractionHandler.Instance != null)
|
||||
{
|
||||
InteractionHandler.Instance.onObjectInteracted -= HandleInteraction;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0b4fa2d4dfc4b6c0fa009fa452a1b5d7
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a26f32de43b8f9d6abb4c6faa954b06b
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,39 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace Quest_Environment.Q3
|
||||
{
|
||||
public class PickupRagAction : MonoBehaviour, IInteractable
|
||||
{
|
||||
[Header("Settings")]
|
||||
public ItemData ragItemData;
|
||||
|
||||
public void Interact()
|
||||
{
|
||||
if (!(QuestManager.Instance?.currentQuest is Q3_WipeSurfacesQuest))
|
||||
{
|
||||
Debug.Log("I have no reason to pick this up right now.");
|
||||
return;
|
||||
}
|
||||
|
||||
bool added = InventorySystem.Instance.AddItem(ragItemData);
|
||||
|
||||
if (added)
|
||||
{
|
||||
if (InteractionHandler.Instance != null)
|
||||
{
|
||||
InteractionHandler.Instance.NotifyInteraction(gameObject);
|
||||
}
|
||||
Destroy(gameObject);
|
||||
}
|
||||
}
|
||||
|
||||
public string GetDescription()
|
||||
{
|
||||
if (QuestManager.Instance?.currentQuest is Q3_WipeSurfacesQuest)
|
||||
{
|
||||
return "Take the rag";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7d76b6445428c35d38032c814918904f
|
||||
@@ -0,0 +1,144 @@
|
||||
using UnityEngine;
|
||||
using Player;
|
||||
|
||||
namespace Quest_Environment.Q3
|
||||
{
|
||||
public class Q3_WipeSurfacesQuest : MonoBehaviour, IQuest
|
||||
{
|
||||
[Header("Quest Settings")]
|
||||
[SerializeField] private string questName = "Surface Wiping";
|
||||
[SerializeField] private int surfacesToWipeTotal = 3;
|
||||
[SerializeField] private ItemData ragItem;
|
||||
|
||||
[Header("Target Tags")]
|
||||
[SerializeField] private string ragGiverTag = "RagLocation";
|
||||
[SerializeField] private string surfaceTag = "WipeableSurface";
|
||||
|
||||
[Header("Audio Settings")]
|
||||
[SerializeField] private AudioClip pickupRagSound;
|
||||
[SerializeField] private AudioClip wipeSurfaceSound;
|
||||
|
||||
private PlayerController _playerController;
|
||||
|
||||
private enum Stage
|
||||
{
|
||||
NotStarted,
|
||||
FindRag,
|
||||
WipeSurfaces,
|
||||
Completed
|
||||
}
|
||||
|
||||
private Stage currentStage = Stage.NotStarted;
|
||||
private int wipedSurfacesCount = 0;
|
||||
|
||||
public string QuestName => questName;
|
||||
public string Description { get; private set; }
|
||||
public int CurrentStep => wipedSurfacesCount;
|
||||
public int TotalSteps => surfacesToWipeTotal;
|
||||
public bool IsCompleted => currentStage == Stage.Completed;
|
||||
|
||||
public event System.Action<string> OnQuestStepChanged;
|
||||
|
||||
public void StartQuest()
|
||||
{
|
||||
if (ragItem == null) Debug.LogError($"[Q3] Rag ItemData is missing!");
|
||||
|
||||
currentStage = Stage.FindRag;
|
||||
wipedSurfacesCount = 0;
|
||||
PlayerHandsController.Instance?.HideHands();
|
||||
|
||||
_playerController = FindObjectOfType<PlayerController>();
|
||||
|
||||
if (InteractionHandler.Instance != null)
|
||||
{
|
||||
InteractionHandler.Instance.onObjectInteracted += HandleInteraction;
|
||||
}
|
||||
UpdateQuestState();
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
if (InteractionHandler.Instance != null)
|
||||
{
|
||||
InteractionHandler.Instance.onObjectInteracted -= HandleInteraction;
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleInteraction(GameObject obj)
|
||||
{
|
||||
if (currentStage == Stage.Completed || obj == null) return;
|
||||
|
||||
switch (currentStage)
|
||||
{
|
||||
case Stage.FindRag:
|
||||
if (obj.CompareTag(ragGiverTag))
|
||||
{
|
||||
currentStage = Stage.WipeSurfaces;
|
||||
_playerController?.PlayOneShotSound(pickupRagSound);
|
||||
PlayerHandsController.Instance?.ShowRag(true);
|
||||
UpdateQuestState();
|
||||
}
|
||||
break;
|
||||
|
||||
case Stage.WipeSurfaces:
|
||||
if (obj.CompareTag(surfaceTag))
|
||||
{
|
||||
wipedSurfacesCount++;
|
||||
_playerController?.PlayOneShotSound(wipeSurfaceSound);
|
||||
QuestManager.Instance.StepCompleted();
|
||||
|
||||
if (wipedSurfacesCount >= surfacesToWipeTotal)
|
||||
{
|
||||
FinishQuest();
|
||||
}
|
||||
else
|
||||
{
|
||||
UpdateQuestState();
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateQuestState()
|
||||
{
|
||||
switch (currentStage)
|
||||
{
|
||||
case Stage.FindRag:
|
||||
Description = "Find a rag.";
|
||||
break;
|
||||
case Stage.WipeSurfaces:
|
||||
Description = "Wipe the dirty surfaces.";
|
||||
break;
|
||||
case Stage.Completed:
|
||||
Description = "Everything is clean!";
|
||||
break;
|
||||
}
|
||||
OnQuestStepChanged?.Invoke(Description);
|
||||
}
|
||||
|
||||
private void FinishQuest()
|
||||
{
|
||||
currentStage = Stage.Completed;
|
||||
|
||||
// Hide the rag and remove it from inventory
|
||||
PlayerHandsController.Instance?.ShowRag(false);
|
||||
if (ragItem != null)
|
||||
{
|
||||
InventorySystem.Instance.RemoveItem(ragItem);
|
||||
}
|
||||
|
||||
UpdateQuestState();
|
||||
QuestManager.Instance.CompleteQuest();
|
||||
}
|
||||
|
||||
public void AdvanceQuestStep() { }
|
||||
public void CompleteQuest()
|
||||
{
|
||||
if (InteractionHandler.Instance != null)
|
||||
{
|
||||
InteractionHandler.Instance.onObjectInteracted -= HandleInteraction;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: eb2201aaa904246a1934c0d3e6804e7a
|
||||
@@ -0,0 +1,75 @@
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Quest_Environment.Q3
|
||||
{
|
||||
public class WipeableSurface : MonoBehaviour, IInteractable
|
||||
{
|
||||
[Header("Settings")]
|
||||
public ItemData requiredRagItem;
|
||||
[SerializeField] private float wipeDuration = 1.0f;
|
||||
|
||||
[Header("Object References")]
|
||||
[Tooltip("The clean version of the surface to be activated.")]
|
||||
[SerializeField] private GameObject cleanSurfaceObject;
|
||||
[Tooltip("The dirty version of the surface to be deactivated.")]
|
||||
[SerializeField] private GameObject dirtySurfaceObject;
|
||||
|
||||
private bool isWiping = false;
|
||||
|
||||
private void Start()
|
||||
{
|
||||
// Ensure the clean version is hidden at the start
|
||||
if (cleanSurfaceObject != null) cleanSurfaceObject.SetActive(false);
|
||||
}
|
||||
|
||||
public void Interact()
|
||||
{
|
||||
if (isWiping) return;
|
||||
|
||||
bool hasRag = InventorySystem.Instance.HasItem(requiredRagItem);
|
||||
|
||||
if (hasRag)
|
||||
{
|
||||
if (QuestManager.Instance != null && QuestManager.Instance.currentQuest is Q3_WipeSurfacesQuest)
|
||||
{
|
||||
StartCoroutine(WipeRoutine());
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Log("This is dirty, but I have no reason to clean it right now.");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Log("A rag is needed to clean this!");
|
||||
}
|
||||
}
|
||||
|
||||
private IEnumerator WipeRoutine()
|
||||
{
|
||||
isWiping = true;
|
||||
|
||||
PlayerHandsController.Instance?.PlayWipeAnimation();
|
||||
InteractionHandler.Instance.NotifyInteraction(gameObject);
|
||||
|
||||
// Wait for the animation to finish
|
||||
yield return new WaitForSeconds(wipeDuration);
|
||||
|
||||
if (dirtySurfaceObject != null) dirtySurfaceObject.SetActive(false);
|
||||
if (cleanSurfaceObject != null) cleanSurfaceObject.SetActive(true);
|
||||
|
||||
Debug.Log("Surface wiped clean!");
|
||||
|
||||
// We don't destroy the parent object, just disable this script
|
||||
// to prevent further interaction.
|
||||
this.enabled = false;
|
||||
}
|
||||
|
||||
public string GetDescription()
|
||||
{
|
||||
if (isWiping || !this.enabled) return "";
|
||||
return "Wipe surface";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0b03ffff37f14870a99dcbcc6b88f3ce
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9fbcdb85dcc14fe6920c2d097cf58197
|
||||
timeCreated: 1764886783
|
||||
@@ -0,0 +1,99 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace Quest_Environment.Q4
|
||||
{
|
||||
[RequireComponent(typeof(Collider))]
|
||||
public class FurniturePlacementZone : MonoBehaviour, IInteractable
|
||||
{
|
||||
[Tooltip("The ID of the furniture that belongs in this zone.")]
|
||||
[SerializeField] private string targetFurnitureId;
|
||||
[Tooltip("The furniture object to show when placed.")]
|
||||
[SerializeField] private GameObject placedFurniturePrefab;
|
||||
[Tooltip("The GameObject with an Outline component that acts as a visual indicator.")]
|
||||
[SerializeField] private GameObject zoneIndicator;
|
||||
|
||||
private bool _isOccupied = false;
|
||||
private Outline _indicatorOutline; // *** НОВОЕ ПОЛЕ для хранения компонента
|
||||
|
||||
void Start()
|
||||
{
|
||||
// *** ИЗМЕНЕНИЕ: Находим и кэшируем компонент Outline
|
||||
if (zoneIndicator != null)
|
||||
{
|
||||
_indicatorOutline = zoneIndicator.GetComponent<Outline>();
|
||||
}
|
||||
ResetZone();
|
||||
}
|
||||
|
||||
public void Interact()
|
||||
{
|
||||
if (QuestManager.Instance?.currentQuest is Q4_PlaceFurnitureQuest furnitureQuest)
|
||||
{
|
||||
if (!_isOccupied && furnitureQuest.HeldFurnitureId == targetFurnitureId)
|
||||
{
|
||||
InteractionHandler.Instance.NotifyInteraction(gameObject);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public string GetDescription()
|
||||
{
|
||||
if (QuestManager.Instance?.currentQuest is Q4_PlaceFurnitureQuest furnitureQuest)
|
||||
{
|
||||
if (!_isOccupied && furnitureQuest.HeldFurnitureId == targetFurnitureId)
|
||||
{
|
||||
return $"Поставить {targetFurnitureId}";
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
public void PlaceItem()
|
||||
{
|
||||
_isOccupied = true;
|
||||
if (placedFurniturePrefab != null) placedFurniturePrefab.SetActive(true);
|
||||
|
||||
// *** ИЗМЕНЕНИЕ: Выключаем Outline через компонент
|
||||
if (_indicatorOutline != null)
|
||||
{
|
||||
_indicatorOutline.enabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
public void ResetZone()
|
||||
{
|
||||
_isOccupied = false;
|
||||
if (placedFurniturePrefab != null) placedFurniturePrefab.SetActive(false);
|
||||
|
||||
// *** ИЗМЕНЕНИЕ: Выключаем Outline через компонент
|
||||
if (_indicatorOutline != null)
|
||||
{
|
||||
_indicatorOutline.enabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
// Если у нас нет компонента подсветки или зона уже занята, ничего не делаем
|
||||
if (_indicatorOutline == null || _isOccupied)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
bool shouldBeActive = false;
|
||||
if (QuestManager.Instance?.currentQuest is Q4_PlaceFurnitureQuest furnitureQuest)
|
||||
{
|
||||
if (furnitureQuest.HeldFurnitureId == targetFurnitureId)
|
||||
{
|
||||
shouldBeActive = true;
|
||||
}
|
||||
}
|
||||
|
||||
// *** ИЗМЕНЕНИЕ: Включаем/выключаем сам компонент, а не весь GameObject
|
||||
if (_indicatorOutline.enabled != shouldBeActive)
|
||||
{
|
||||
_indicatorOutline.enabled = shouldBeActive;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5a6c0505d876d3b9087aca44c7e5e5db
|
||||
@@ -0,0 +1,36 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace Quest_Environment.Q4
|
||||
{
|
||||
[RequireComponent(typeof(Outline))]
|
||||
public class MovableFurniture : MonoBehaviour, IInteractable
|
||||
{
|
||||
[Tooltip("A unique ID for this piece of furniture (e.g., 'Chair', 'Lamp').")]
|
||||
[SerializeField] private string furnitureId;
|
||||
|
||||
public void Interact()
|
||||
{
|
||||
// Проверяем, что сейчас идет квест с мебелью, прежде чем что-то делать
|
||||
if (QuestManager.Instance?.currentQuest is Q4_PlaceFurnitureQuest)
|
||||
{
|
||||
InteractionHandler.Instance.NotifyInteraction(gameObject);
|
||||
}
|
||||
}
|
||||
|
||||
public string GetDescription()
|
||||
{
|
||||
// Описание будет только если активен квест по расстановке мебели
|
||||
if (QuestManager.Instance?.currentQuest is Q4_PlaceFurnitureQuest furnitureQuest)
|
||||
{
|
||||
// И если игрок ничего не "держит" в руках
|
||||
if (furnitureQuest.HeldFurnitureId == null)
|
||||
{
|
||||
return $"Подобрать {furnitureId}";
|
||||
}
|
||||
}
|
||||
|
||||
// В противном случае возвращаем пустую строку, и подсветки не будет
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 21362de71083aec96a3b66b617e67ee1
|
||||
@@ -0,0 +1,136 @@
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace Quest_Environment.Q4
|
||||
{
|
||||
public class Q4_PlaceFurnitureQuest : MonoBehaviour, IQuest
|
||||
{
|
||||
[System.Serializable]
|
||||
public class FurnitureTask
|
||||
{
|
||||
public string furnitureId;
|
||||
[Tooltip("The object that can be picked up.")]
|
||||
public GameObject pickupObject;
|
||||
[Tooltip("The zone where the object should be placed.")]
|
||||
public FurniturePlacementZone placementZone;
|
||||
[HideInInspector] public bool isPlaced;
|
||||
}
|
||||
|
||||
[Header("Quest Settings")]
|
||||
[SerializeField] private string questName = "Tidy Up the Room";
|
||||
[SerializeField] private List<FurnitureTask> furnitureTasks;
|
||||
|
||||
private string _heldFurnitureId = null;
|
||||
private int _placedCount = 0;
|
||||
|
||||
public string QuestName => questName;
|
||||
public string Description { get; private set; }
|
||||
public int CurrentStep => _placedCount;
|
||||
public int TotalSteps => furnitureTasks.Count;
|
||||
public bool IsCompleted => _placedCount >= TotalSteps;
|
||||
|
||||
public string HeldFurnitureId => _heldFurnitureId;
|
||||
|
||||
public event System.Action<string> OnQuestStepChanged;
|
||||
|
||||
public void StartQuest()
|
||||
{
|
||||
_placedCount = 0;
|
||||
_heldFurnitureId = null;
|
||||
foreach (var task in furnitureTasks)
|
||||
{
|
||||
task.isPlaced = false;
|
||||
if (task.placementZone != null) task.placementZone.ResetZone();
|
||||
if (task.pickupObject != null) task.pickupObject.SetActive(true);
|
||||
}
|
||||
|
||||
PlayerHandsController.Instance?.HideHands();
|
||||
if (InteractionHandler.Instance != null)
|
||||
{
|
||||
InteractionHandler.Instance.onObjectInteracted += HandleInteraction;
|
||||
}
|
||||
UpdateQuestState();
|
||||
}
|
||||
|
||||
void OnDestroy()
|
||||
{
|
||||
if (InteractionHandler.Instance != null)
|
||||
{
|
||||
InteractionHandler.Instance.onObjectInteracted -= HandleInteraction;
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleInteraction(GameObject interactedObject)
|
||||
{
|
||||
if (IsCompleted) return;
|
||||
|
||||
if (_heldFurnitureId == null)
|
||||
{
|
||||
var task = furnitureTasks.FirstOrDefault(t => !t.isPlaced && t.pickupObject == interactedObject);
|
||||
if (task != null)
|
||||
{
|
||||
_heldFurnitureId = task.furnitureId;
|
||||
task.pickupObject.SetActive(false);
|
||||
UpdateQuestState();
|
||||
return;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var task = furnitureTasks.FirstOrDefault(t => t.furnitureId == _heldFurnitureId && t.placementZone.gameObject == interactedObject);
|
||||
if (task != null)
|
||||
{
|
||||
task.isPlaced = true;
|
||||
task.placementZone.PlaceItem();
|
||||
_heldFurnitureId = null;
|
||||
_placedCount++;
|
||||
QuestManager.Instance.StepCompleted();
|
||||
|
||||
if (IsCompleted)
|
||||
{
|
||||
FinishQuest();
|
||||
}
|
||||
else
|
||||
{
|
||||
UpdateQuestState();
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateQuestState()
|
||||
{
|
||||
if (IsCompleted)
|
||||
{
|
||||
Description = "Everything is in its place!";
|
||||
}
|
||||
else if (_heldFurnitureId != null)
|
||||
{
|
||||
Description = $"Place the {_heldFurnitureId}.";
|
||||
}
|
||||
else
|
||||
{
|
||||
Description = $"Arrange the furniture: {_placedCount} / {TotalSteps}";
|
||||
}
|
||||
OnQuestStepChanged?.Invoke(Description);
|
||||
}
|
||||
|
||||
private void FinishQuest()
|
||||
{
|
||||
UpdateQuestState();
|
||||
QuestManager.Instance.CompleteQuest();
|
||||
}
|
||||
|
||||
public void AdvanceQuestStep() { }
|
||||
|
||||
public void CompleteQuest()
|
||||
{
|
||||
if (InteractionHandler.Instance != null)
|
||||
{
|
||||
InteractionHandler.Instance.onObjectInteracted -= HandleInteraction;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 016d18b175bddbe869252563f50f76c7
|
||||
@@ -0,0 +1,31 @@
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
|
||||
[CreateAssetMenu(fileName = "NewQuest", menuName = "Quest System/Quest")]
|
||||
public class Quest : ScriptableObject
|
||||
{
|
||||
[Header("General Info")]
|
||||
public string questTitle = "Название Квеста";
|
||||
public bool isCompleted = false;
|
||||
|
||||
[Header("Steps")]
|
||||
public List<QuestStepData> steps = new List<QuestStepData>();
|
||||
}
|
||||
|
||||
[System.Serializable]
|
||||
public class QuestStepData
|
||||
{
|
||||
[Header("Step Info")]
|
||||
public string stepDescription = "Описание текущей задачи";
|
||||
|
||||
[Tooltip("Префаб, который будет создан в сцене для управления логикой этого шага.")]
|
||||
public GameObject stepPrefab;
|
||||
|
||||
[Tooltip("Список конкретных объектов в сцене, с которыми нужно взаимодействовать.")]
|
||||
public GameObject[] targetObjects;
|
||||
|
||||
public bool isCompleted = false;
|
||||
|
||||
[Tooltip("ID жуткого события, которое вызывается после завершения этого шага.")]
|
||||
public string spookyEventID = "";
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 89a79b6cc5da45a18e916924bceac2ec
|
||||
timeCreated: 1764499632
|
||||
@@ -0,0 +1,112 @@
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
public class QuestManager : MonoBehaviour
|
||||
{
|
||||
public static QuestManager Instance;
|
||||
|
||||
[SerializeField] private List<GameObject> questPrefabs;
|
||||
private List<IQuest> allQuests = new List<IQuest>();
|
||||
|
||||
private IQuest _currentQuest;
|
||||
public IQuest currentQuest => _currentQuest;
|
||||
|
||||
public bool isStarted;
|
||||
|
||||
public event System.Action<IQuest> OnQuestStarted;
|
||||
public event System.Action<IQuest> OnQuestCompleted;
|
||||
public event System.Action<string> OnQuestStepChanged;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
if (Instance == null)
|
||||
{
|
||||
Instance = this;
|
||||
DontDestroyOnLoad(gameObject);
|
||||
|
||||
foreach (var qObj in questPrefabs)
|
||||
{
|
||||
var q = qObj.GetComponent<IQuest>();
|
||||
if (q != null) allQuests.Add(q);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Destroy(gameObject);
|
||||
}
|
||||
}
|
||||
|
||||
void Start()
|
||||
{
|
||||
if (isStarted) StartFirstQuest();
|
||||
}
|
||||
|
||||
public void StartFirstQuest()
|
||||
{
|
||||
if (allQuests.Count > 0) StartQuest(allQuests[0]);
|
||||
}
|
||||
|
||||
public void StartQuest(IQuest quest)
|
||||
{
|
||||
if (_currentQuest != null && !_currentQuest.IsCompleted)
|
||||
{
|
||||
Debug.Log($"[QuestManager] Quest '{_currentQuest.QuestName}' is not completed yet.");
|
||||
return;
|
||||
}
|
||||
|
||||
_currentQuest = quest;
|
||||
_currentQuest.OnQuestStepChanged += HandleQuestStepChanged;
|
||||
_currentQuest.StartQuest();
|
||||
|
||||
Debug.Log($"[QuestManager] Started quest: {quest.QuestName}");
|
||||
OnQuestStarted?.Invoke(_currentQuest);
|
||||
|
||||
HandleQuestStepChanged(_currentQuest.Description);
|
||||
}
|
||||
|
||||
public void CompleteQuest()
|
||||
{
|
||||
if (_currentQuest != null)
|
||||
{
|
||||
Debug.Log($"[QuestManager] Quest '{_currentQuest.QuestName}' COMPLETED!");
|
||||
_currentQuest.OnQuestStepChanged -= HandleQuestStepChanged;
|
||||
_currentQuest.CompleteQuest();
|
||||
OnQuestCompleted?.Invoke(_currentQuest);
|
||||
|
||||
var completedQuest = _currentQuest;
|
||||
_currentQuest = null;
|
||||
|
||||
int completedIndex = allQuests.IndexOf(completedQuest);
|
||||
if (completedIndex >= 0 && completedIndex + 1 < allQuests.Count)
|
||||
{
|
||||
StartQuest(allQuests[completedIndex + 1]);
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Log("[QuestManager] All quests completed!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void AdvanceCurrentQuestStep()
|
||||
{
|
||||
if (_currentQuest != null)
|
||||
{
|
||||
_currentQuest.AdvanceQuestStep();
|
||||
}
|
||||
}
|
||||
|
||||
public void StepCompleted()
|
||||
{
|
||||
if (_currentQuest != null)
|
||||
{
|
||||
_currentQuest.AdvanceQuestStep();
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleQuestStepChanged(string description)
|
||||
{
|
||||
OnQuestStepChanged?.Invoke(description);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 44faba98ac5c4c9da043cc53a39b1c6a
|
||||
timeCreated: 1764499686
|
||||
@@ -0,0 +1,88 @@
|
||||
using UnityEngine;
|
||||
using TMPro; // Необходимо для работы с TextMeshPro
|
||||
|
||||
/// <summary>
|
||||
/// Управляет отображением информации о квесте в UI.
|
||||
/// Подписывается на события QuestManager и обновляет текстовые поля.
|
||||
/// </summary>
|
||||
public class QuestUIController : MonoBehaviour
|
||||
{
|
||||
[Header("UI Элементы")]
|
||||
[Tooltip("Родительский объект всего UI квеста, чтобы его можно было скрывать и показывать.")]
|
||||
[SerializeField] private GameObject questUIPanel;
|
||||
|
||||
[Tooltip("Текстовое поле для описания задания. Например: 'Соберите мусор'.")]
|
||||
[SerializeField] private TextMeshProUGUI taskDescriptionText;
|
||||
|
||||
[Tooltip("Текстовое поле для отображения прогресса. Например: '1 / 3'.")]
|
||||
[SerializeField] private TextMeshProUGUI taskProgressText;
|
||||
|
||||
|
||||
void Start()
|
||||
{
|
||||
// Проверяем, найден ли QuestManager
|
||||
if (QuestManager.Instance == null)
|
||||
{
|
||||
Debug.LogError("QuestUIController не может найти QuestManager.Instance! UI не будет работать.");
|
||||
// Выключаем панель, чтобы не было видно пустого UI
|
||||
if(questUIPanel != null) questUIPanel.SetActive(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Подписываемся на события QuestManager
|
||||
QuestManager.Instance.OnQuestStarted += HandleQuestStarted;
|
||||
QuestManager.Instance.OnQuestCompleted += HandleQuestCompleted;
|
||||
QuestManager.Instance.OnQuestStepChanged += UpdateQuestDescription;
|
||||
|
||||
// Изначально скрываем UI
|
||||
if(questUIPanel != null) questUIPanel.SetActive(false);
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
// Отписываемся от событий, чтобы избежать ошибок
|
||||
if (QuestManager.Instance != null)
|
||||
{
|
||||
QuestManager.Instance.OnQuestStarted -= HandleQuestStarted;
|
||||
QuestManager.Instance.OnQuestCompleted -= HandleQuestCompleted;
|
||||
QuestManager.Instance.OnQuestStepChanged -= UpdateQuestDescription;
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleQuestStarted(IQuest quest)
|
||||
{
|
||||
if(questUIPanel != null) questUIPanel.SetActive(true);
|
||||
UpdateQuestDescription(quest.Description);
|
||||
}
|
||||
|
||||
private void HandleQuestCompleted(IQuest quest)
|
||||
{
|
||||
// Когда квест завершен, просто скрываем панель.
|
||||
// Можно добавить анимацию или сообщение "Квест выполнен!"
|
||||
if(questUIPanel != null) questUIPanel.SetActive(false);
|
||||
}
|
||||
|
||||
private void UpdateQuestDescription(string description)
|
||||
{
|
||||
if (taskDescriptionText != null)
|
||||
{
|
||||
taskDescriptionText.text = description;
|
||||
}
|
||||
|
||||
// Обновляем прогресс, если квест активен
|
||||
if (QuestManager.Instance.currentQuest != null && !QuestManager.Instance.currentQuest.IsCompleted)
|
||||
{
|
||||
if (taskProgressText != null)
|
||||
{
|
||||
taskProgressText.text = $"{QuestManager.Instance.currentQuest.CurrentStep} / {QuestManager.Instance.currentQuest.TotalSteps}";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (taskProgressText != null)
|
||||
{
|
||||
taskProgressText.text = ""; // Очищаем прогресс, если квеста нет
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6cacb6ef727cdd942b2c045e8aad601c
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 364488bc02534c258718d9af2009884a
|
||||
timeCreated: 1764499771
|
||||
@@ -0,0 +1,202 @@
|
||||
using Player;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Quests
|
||||
{
|
||||
public class Q1CollectGarbageQuest : MonoBehaviour, IQuest
|
||||
{
|
||||
[Header("Quest Settings")]
|
||||
[SerializeField] private string questName = "Clean Up The Area";
|
||||
[SerializeField] private int trashItemsPerBag = 3;
|
||||
[SerializeField] private int bagsToDisposeTotal = 2;
|
||||
[SerializeField] private ItemData garbageBagItem;
|
||||
|
||||
[Header("Звуки Квеста")]
|
||||
[SerializeField] private AudioClip pickupBagSound;
|
||||
[SerializeField] private AudioClip collectTrashSound;
|
||||
[SerializeField] private AudioClip disposeBagSound;
|
||||
private PlayerController _playerController;
|
||||
|
||||
[Header("Target Tags")]
|
||||
[SerializeField] private string bagGiverTag = "TrashBagBox";
|
||||
[SerializeField] private string trashTag = "Trash";
|
||||
[SerializeField] private string dumpsterTag = "Dumpster";
|
||||
|
||||
private enum Stage
|
||||
{
|
||||
NotStarted,
|
||||
FindBag,
|
||||
FillBag,
|
||||
DisposeBag,
|
||||
Completed
|
||||
}
|
||||
|
||||
private Stage currentStage = Stage.NotStarted;
|
||||
private int currentTrashInBag = 0;
|
||||
private int disposedBagsCount = 0;
|
||||
|
||||
public string QuestName => questName;
|
||||
public string Description { get; private set; }
|
||||
public int CurrentStep => disposedBagsCount;
|
||||
public int TotalSteps => bagsToDisposeTotal;
|
||||
public bool IsCompleted => currentStage == Stage.Completed;
|
||||
|
||||
public event System.Action<string> OnQuestStepChanged;
|
||||
|
||||
public void StartQuest()
|
||||
{
|
||||
if (garbageBagItem == null)
|
||||
{
|
||||
Debug.LogError("[QUEST START CHECK] Reference to 'garbageBagItem' is NULL when the quest starts. Check the quest object's inspector on the scene!");
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Log($"[QUEST START CHECK] Reference to 'garbageBagItem' is SET. Item: '{garbageBagItem.itemName}'.");
|
||||
}
|
||||
|
||||
currentStage = Stage.FindBag;
|
||||
disposedBagsCount = 0;
|
||||
currentTrashInBag = 0;
|
||||
PlayerHandsController.Instance?.HideHands();
|
||||
if (InteractionHandler.Instance != null)
|
||||
{
|
||||
InteractionHandler.Instance.onObjectInteracted += HandleInteraction;
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogError("InteractionHandler not found! The quest will not work.");
|
||||
}
|
||||
_playerController = Object.FindFirstObjectByType<PlayerController>();
|
||||
UpdateQuestState();
|
||||
}
|
||||
|
||||
void OnDestroy()
|
||||
{
|
||||
if (InteractionHandler.Instance != null)
|
||||
{
|
||||
InteractionHandler.Instance.onObjectInteracted -= HandleInteraction;
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleInteraction(GameObject obj)
|
||||
{
|
||||
if (currentStage == Stage.Completed || obj == null) return;
|
||||
|
||||
switch (currentStage)
|
||||
{
|
||||
case Stage.FindBag:
|
||||
if (obj.CompareTag(bagGiverTag))
|
||||
{
|
||||
currentStage = Stage.FillBag;
|
||||
currentTrashInBag = 0;
|
||||
PlayerHandsController.Instance?.ShowBag(false);
|
||||
_playerController?.PlayOneShotSound(pickupBagSound);
|
||||
UpdateQuestState();
|
||||
}
|
||||
break;
|
||||
|
||||
case Stage.FillBag:
|
||||
if (obj.CompareTag(trashTag))
|
||||
{
|
||||
currentTrashInBag++;
|
||||
_playerController?.PlayOneShotSound(collectTrashSound);
|
||||
if (currentTrashInBag >= trashItemsPerBag)
|
||||
{
|
||||
currentStage = Stage.DisposeBag;
|
||||
PlayerHandsController.Instance?.ShowBag(true);
|
||||
}
|
||||
UpdateQuestState();
|
||||
}
|
||||
break;
|
||||
|
||||
case Stage.DisposeBag:
|
||||
if (obj.CompareTag(dumpsterTag))
|
||||
{
|
||||
if (garbageBagItem != null)
|
||||
{
|
||||
InventorySystem.Instance.RemoveItem(garbageBagItem);
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogError("ItemData for the garbage bag is not specified in the quest!");
|
||||
}
|
||||
|
||||
PlayerHandsController.Instance?.HideHands();
|
||||
_playerController?.PlayOneShotSound(disposeBagSound);
|
||||
disposedBagsCount++;
|
||||
QuestManager.Instance.StepCompleted();
|
||||
|
||||
if (disposedBagsCount >= bagsToDisposeTotal)
|
||||
{
|
||||
FinishQuest();
|
||||
}
|
||||
else
|
||||
{
|
||||
currentStage = Stage.FindBag;
|
||||
UpdateQuestState();
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateQuestState()
|
||||
{
|
||||
switch (currentStage)
|
||||
{
|
||||
case Stage.FindBag:
|
||||
Description = "Find a roll of trash bags.";
|
||||
break;
|
||||
case Stage.FillBag:
|
||||
Description = $"Collect trash in the bag: {currentTrashInBag} / {trashItemsPerBag}";
|
||||
break;
|
||||
case Stage.DisposeBag:
|
||||
Description = "Dispose of the full bag in the dumpster.";
|
||||
break;
|
||||
case Stage.Completed:
|
||||
Description = "Clean-up complete!";
|
||||
break;
|
||||
}
|
||||
OnQuestStepChanged?.Invoke(Description);
|
||||
}
|
||||
|
||||
public void AdvanceQuestStep() { }
|
||||
|
||||
public bool IsBagFull()
|
||||
{
|
||||
if (currentStage == Stage.DisposeBag) return true;
|
||||
if (currentStage == Stage.FillBag) return currentTrashInBag >= trashItemsPerBag;
|
||||
return false;
|
||||
}
|
||||
|
||||
private void FinishQuest()
|
||||
{
|
||||
currentStage = Stage.Completed;
|
||||
UpdateQuestState();
|
||||
QuestManager.Instance.CompleteQuest();
|
||||
}
|
||||
|
||||
public void CompleteQuest()
|
||||
{
|
||||
PlayerHandsController.Instance?.HideHands();
|
||||
if (InteractionHandler.Instance != null)
|
||||
{
|
||||
InteractionHandler.Instance.onObjectInteracted -= HandleInteraction;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(bagGiverTag))
|
||||
{
|
||||
GameObject bagGiver = GameObject.FindGameObjectWithTag(bagGiverTag);
|
||||
if (bagGiver != null)
|
||||
{
|
||||
Object.Destroy(bagGiver);
|
||||
Debug.Log($"Quest '{QuestName}' completed. Bag source '{bagGiver.name}' destroyed.");
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogWarning($"Quest '{QuestName}' completed, but could not find the bag source with tag '{bagGiverTag}'.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e0aed862f90a49d8bcd8e32dad4dcbfd
|
||||
timeCreated: 1764499781
|
||||
@@ -0,0 +1,138 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace Quests
|
||||
{
|
||||
public class Q2SweepDirtQuest : MonoBehaviour, IQuest
|
||||
{
|
||||
[Header("Quest Settings")]
|
||||
[SerializeField] private string questName = "Уборка помещений";
|
||||
[SerializeField] private int dirtPilesTotal = 5;
|
||||
[SerializeField] private ItemData broomItem;
|
||||
|
||||
[Header("Target Tags")]
|
||||
[SerializeField] private string broomGiverTag = "BroomLocation"; // Тэг места, где стоит метла
|
||||
[SerializeField] private string dirtTag = "Dirt"; // Тэг самой грязи
|
||||
|
||||
private enum Stage
|
||||
{
|
||||
NotStarted,
|
||||
FindBroom,
|
||||
SweepDirt,
|
||||
Completed
|
||||
}
|
||||
|
||||
private Stage currentStage = Stage.NotStarted;
|
||||
private int cleanedDirtCount = 0;
|
||||
|
||||
public string QuestName => questName;
|
||||
public string Description { get; private set; }
|
||||
public int CurrentStep => cleanedDirtCount;
|
||||
public int TotalSteps => dirtPilesTotal;
|
||||
public bool IsCompleted => currentStage == Stage.Completed;
|
||||
|
||||
public event System.Action<string> OnQuestStepChanged;
|
||||
|
||||
public void StartQuest()
|
||||
{
|
||||
if (broomItem == null) Debug.LogError($"[Q2] Broom ItemData is missing!");
|
||||
|
||||
currentStage = Stage.FindBroom;
|
||||
cleanedDirtCount = 0;
|
||||
|
||||
// Скрываем руки (убираем мусорный мешок из прошлого квеста)
|
||||
PlayerHandsController.Instance?.HideHands();
|
||||
|
||||
if (InteractionHandler.Instance != null)
|
||||
{
|
||||
InteractionHandler.Instance.onObjectInteracted += HandleInteraction;
|
||||
}
|
||||
UpdateQuestState();
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
if (InteractionHandler.Instance != null)
|
||||
{
|
||||
InteractionHandler.Instance.onObjectInteracted -= HandleInteraction;
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleInteraction(GameObject obj)
|
||||
{
|
||||
if (currentStage == Stage.Completed || obj == null) return;
|
||||
|
||||
switch (currentStage)
|
||||
{
|
||||
case Stage.FindBroom:
|
||||
// Если игрок взаимодействовал с объектом метлы (поднял её)
|
||||
if (obj.CompareTag(broomGiverTag))
|
||||
{
|
||||
currentStage = Stage.SweepDirt;
|
||||
|
||||
// Показываем визуальную метлу в руках
|
||||
PlayerHandsController.Instance?.ShowBroom(true);
|
||||
|
||||
UpdateQuestState();
|
||||
}
|
||||
break;
|
||||
|
||||
case Stage.SweepDirt:
|
||||
// Если игрок взаимодействовал с грязью
|
||||
if (obj.CompareTag(dirtTag))
|
||||
{
|
||||
cleanedDirtCount++;
|
||||
QuestManager.Instance.StepCompleted();
|
||||
|
||||
if (cleanedDirtCount >= dirtPilesTotal)
|
||||
{
|
||||
FinishQuest();
|
||||
}
|
||||
else
|
||||
{
|
||||
UpdateQuestState();
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateQuestState()
|
||||
{
|
||||
switch (currentStage)
|
||||
{
|
||||
case Stage.FindBroom:
|
||||
Description = "Найдите метлу.";
|
||||
break;
|
||||
case Stage.SweepDirt:
|
||||
Description = $"Подметите пол в комнатах: {cleanedDirtCount} / {dirtPilesTotal}";
|
||||
break;
|
||||
case Stage.Completed:
|
||||
Description = "Пол чист!";
|
||||
break;
|
||||
}
|
||||
OnQuestStepChanged?.Invoke(Description);
|
||||
}
|
||||
|
||||
private void FinishQuest()
|
||||
{
|
||||
currentStage = Stage.Completed;
|
||||
|
||||
// Прячем метлу по завершении
|
||||
PlayerHandsController.Instance?.ShowBroom(false);
|
||||
// Или PlayerHandsController.Instance?.HideHands();
|
||||
|
||||
UpdateQuestState();
|
||||
QuestManager.Instance.CompleteQuest();
|
||||
}
|
||||
|
||||
public void AdvanceQuestStep() { }
|
||||
public void CompleteQuest()
|
||||
{
|
||||
if (InteractionHandler.Instance != null)
|
||||
{
|
||||
InteractionHandler.Instance.onObjectInteracted -= HandleInteraction;
|
||||
}
|
||||
InventorySystem.Instance.RemoveItem(broomItem);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 040b72c86eb545eb9615b16ac561fcea
|
||||
timeCreated: 1764782725
|
||||
Reference in new issue
Block a user