папочка навёл порядок в папках

This commit is contained in:
vladislove committed 2026-07-20 21:07:50 +03:00
1 parent 9374a984e6
commit b407380203
1123 files changed
+2764 -133233

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 7992d593aabcf5245921c04777461800
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,198 @@
using UnityEngine;
public class CameraController : MonoBehaviour
{
[Header("Настройки позиции камеры (Зум)")]
public float distance = 10f;
public float minDistance = 3f;
public float maxDistance = 30f;
public float zoomSpeed = 0.05f;
[Header("Настройки цели (Ось Y)")]
public float targetY = 0f;
public float minTargetY = 0f;
public float maxTargetY = 15f;
public float moveTargetSpeed = 0.02f;
public float addingHeight = 3f;
[Header("Настройки вращения")]
public float rotationSpeed = 0.2f;
[SerializeField]
private float currentAngle = -45f;
[Header("Настройки смещения (Pan - НОВОЕ)")]
[Tooltip("Скорость смещения камеры по горизонтали")]
public float panSpeed = 0.03f;
[Tooltip("При каком отдалении камеры разрешено смещение? (Если отдалить дальше - смещение сбросится)")]
public float zoomThresholdForPan = 15f;
[Tooltip("Максимальное смещение от центра комнаты")]
public float maxPanDistance = 10f;
[Header("Настройки плавности (Сглаживание)")]
[Range(0.01f, 0.5f)]
public float smoothTime = 0.1f;
public float touchDeadZone = 1.5f;
// ЦЕЛЕВЫЕ значения
private float _targetAngle;
private float _targetY;
private float _targetDistance;
// НОВОЕ: Целевое и текущее смещение по осям X и Z
private Vector2 _targetPanOffset;
private Vector2 _currentPanOffset;
// Внутренние переменные скорости для SmoothDamp
private float _angleVelocity;
private float _yVelocity;
private float _distanceVelocity;
private Vector2 _panVelocity; // Скорость для смещения
void Start()
{
_targetAngle = currentAngle;
_targetY = targetY;
_targetDistance = distance;
_targetPanOffset = Vector2.zero;
_currentPanOffset = Vector2.zero;
UpdateCameraPosition();
}
void LateUpdate()
{
HandleInput();
CheckPanReset(); // Проверяем, не пора ли сбросить смещение
SmoothMovement();
UpdateCameraPosition();
}
private void HandleInput()
{
// === 1. УПРАВЛЕНИЕ ОДНИМ ПАЛЬЦЕМ (Вращение и высота) ===
if (Input.touchCount == 1)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Moved && touch.deltaPosition.sqrMagnitude > touchDeadZone * touchDeadZone)
{
_targetAngle += touch.deltaPosition.x * rotationSpeed;
_targetY -= touch.deltaPosition.y * moveTargetSpeed;
_targetY = Mathf.Clamp(_targetY, minTargetY, maxTargetY);
}
}
// === 2. УПРАВЛЕНИЕ ДВУМЯ ПАЛЬЦАМИ (Зум и Смещение) ===
else if (Input.touchCount == 2)
{
Touch touch0 = Input.GetTouch(0);
Touch touch1 = Input.GetTouch(1);
// -- Логика Зума --
Vector2 touch0PrevPos = touch0.position - touch0.deltaPosition;
Vector2 touch1PrevPos = touch1.position - touch1.deltaPosition;
float prevMagnitude = (touch0PrevPos - touch1PrevPos).magnitude;
float currentMagnitude = (touch0.position - touch1.position).magnitude;
float difference = currentMagnitude - prevMagnitude;
if (Mathf.Abs(difference) > touchDeadZone)
{
_targetDistance -= difference * zoomSpeed;
_targetDistance = Mathf.Clamp(_targetDistance, minDistance, maxDistance);
}
// -- НОВОЕ: Логика смещения (Панорамирование) --
// Разрешаем смещение только если камера достаточно близко
if (_targetDistance <= zoomThresholdForPan)
{
// Берем среднее движение двух пальцев
Vector2 avgDelta = (touch0.deltaPosition + touch1.deltaPosition) / 2f;
ApplyPan(avgDelta.x, avgDelta.y);
}
}
// === 3. МЫШЬ (Для редактора ПК) ===
else
{
// Левая кнопка - Вращение и высота
if (Input.GetMouseButton(0))
{
_targetAngle += Input.GetAxis("Mouse X") * rotationSpeed * 20f;
_targetY -= Input.GetAxis("Mouse Y") * moveTargetSpeed * 20f;
_targetY = Mathf.Clamp(_targetY, minTargetY, maxTargetY);
}
// НОВОЕ: Правая кнопка - Смещение (Pan)
else if (Input.GetMouseButton(1) && _targetDistance <= zoomThresholdForPan)
{
ApplyPan(Input.GetAxis("Mouse X") * 20f, Input.GetAxis("Mouse Y") * 20f);
}
// Зум колесиком мыши
float scroll = Input.GetAxis("Mouse ScrollWheel");
if (scroll != 0)
{
_targetDistance -= scroll * zoomSpeed * 100f;
_targetDistance = Mathf.Clamp(_targetDistance, minDistance, maxDistance);
}
}
}
// НОВЫЙ МЕТОД: Применение смещения относительно текущего поворота камеры
private void ApplyPan(float deltaX, float deltaY)
{
// Высчитываем векторы "вправо" и "вперед" для камеры, игнорируя наклон (ось Y)
Vector3 right = transform.right;
right.y = 0;
right.Normalize();
Vector3 forward = transform.forward;
forward.y = 0;
forward.Normalize();
// Умножаем движение пальца/мыши на направление камеры
Vector3 move = (right * -deltaX) + (forward * -deltaY);
_targetPanOffset += new Vector2(move.x, move.z) * panSpeed;
// Ограничиваем максимальное смещение, чтобы не улететь за карту
if (_targetPanOffset.magnitude > maxPanDistance)
{
_targetPanOffset = _targetPanOffset.normalized * maxPanDistance;
}
}
// НОВЫЙ МЕТОД: Сброс смещения при отдалении
private void CheckPanReset()
{
if (_targetDistance > zoomThresholdForPan)
{
// Если отдалились слишком сильно - обнуляем целевое смещение.
// Благодаря SmoothDamp камера вернется в центр плавно!
_targetPanOffset = Vector2.zero;
}
}
private void SmoothMovement()
{
currentAngle = Mathf.SmoothDamp(currentAngle, _targetAngle, ref _angleVelocity, smoothTime);
targetY = Mathf.SmoothDamp(targetY, _targetY, ref _yVelocity, smoothTime);
distance = Mathf.SmoothDamp(distance, _targetDistance, ref _distanceVelocity, smoothTime);
// НОВОЕ: Плавно сглаживаем позицию смещения
_currentPanOffset = Vector2.SmoothDamp(_currentPanOffset, _targetPanOffset, ref _panVelocity, smoothTime);
}
private void UpdateCameraPosition()
{
// НОВОЕ: Теперь цель вращения учитывает наше смещение по осям X и Z
Vector3 targetPoint = new Vector3(_currentPanOffset.x, targetY, _currentPanOffset.y);
float radians = currentAngle * Mathf.Deg2Rad;
float x = targetPoint.x + distance * Mathf.Sin(radians);
float z = targetPoint.z + distance * Mathf.Cos(radians);
transform.position = new Vector3(x, targetY + addingHeight, z);
transform.LookAt(targetPoint);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: f29cc249ac44dd54c967d23bfb3b0316
@@ -0,0 +1,38 @@
using UnityEngine;
using UnityEngine.Rendering;
public class CeilingVisibility : MonoBehaviour
{
private Renderer _renderer;
private Camera _cam;
void Start()
{
_renderer = GetComponent<Renderer>();
_cam = Camera.main;
}
void LateUpdate()
{
if (_cam == null || _renderer == null) return;
// Если камера находится ВЫШЕ потолка
if (_cam.transform.position.y > transform.position.y)
{
// Делаем сам потолок невидимым, но заставляем его отбрасывать тень в комнату!
if (_renderer.shadowCastingMode != ShadowCastingMode.ShadowsOnly)
{
_renderer.shadowCastingMode = ShadowCastingMode.ShadowsOnly;
}
}
else
{
// Если камера опустилась ВНУТРЬ комнаты (ниже потолка)
if (_renderer.shadowCastingMode != ShadowCastingMode.On)
{
// Возвращаем потолку видимость
_renderer.shadowCastingMode = ShadowCastingMode.On;
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 85a21ba56c50a1c4eb56a91f4e77df19
@@ -0,0 +1,333 @@
using UnityEngine;
using UnityEngine.EventSystems;
public class FurnitureController : MonoBehaviour
{
public enum EditTool { Move, Rotate }
[Header("Настройки")]
public GameObject currentPrefab;
public LayerMask floorLayer;
public LayerMask wallLayer;
public LayerMask furnitureLayer;
[SerializeField] private GameObject shopPanel;
[Header("Режим редактирования (UI)")]
[SerializeField] private GameObject editPanel;
[SerializeField] private GameObject rotate90Button;
public float rotationSpeed = 5f;
[Header("Связь с камерой")]
public MonoBehaviour cameraController;
private GameObject _activeFurniture;
private FurnitureObject _activeFurnitureScript;
private EditTool _currentTool = EditTool.Move;
private Camera _cam;
private bool _isInteracting = false;
private Vector3 _lastInputPos;
private Vector3 _dragOffset;
private void Start()
{
_cam = Camera.main;
if (cameraController == null && _cam != null)
cameraController = _cam.GetComponent("CameraController") as MonoBehaviour;
currentPrefab = null;
editPanel.SetActive(false);
if (rotate90Button != null) rotate90Button.SetActive(false);
}
void Update()
{
if (_activeFurniture != null)
{
HandleEditing();
}
else if (currentPrefab != null)
{
if (Input.GetMouseButtonDown(0) && !shopPanel.activeSelf && !IsPointerOverUI())
TryPlaceFurniture();
}
else
{
if (Input.GetMouseButtonDown(0) && !shopPanel.activeSelf && !IsPointerOverUI())
TrySelectPlacedFurniture();
}
}
private void HandleEditing()
{
if (Input.GetMouseButtonDown(0) && !IsPointerOverUI())
{
_lastInputPos = Input.mousePosition;
if (_currentTool == EditTool.Move)
{
Ray ray = _cam.ScreenPointToRay(Input.mousePosition);
RaycastHit[] hits = Physics.SphereCastAll(ray, 0.5f, 100f);
bool foundFurniture = false;
foreach (var hit in hits)
{
if (hit.transform.IsChildOf(_activeFurniture.transform) || hit.transform == _activeFurniture.transform)
{
foundFurniture = true;
break;
}
}
if (foundFurniture)
{
// Для пола считаем смещение, настенные предметы просто цепляем к курсору
if (!_activeFurnitureScript.isWallObject && Physics.Raycast(ray, out RaycastHit floorHit, 100f, floorLayer))
{
_dragOffset = _activeFurniture.transform.position - floorHit.point;
_dragOffset.y = 0;
}
else _dragOffset = Vector3.zero;
StartInteraction();
}
}
else if (_currentTool == EditTool.Rotate)
{
StartInteraction();
}
}
if (Input.GetMouseButton(0) && _isInteracting)
{
Ray ray = _cam.ScreenPointToRay(Input.mousePosition);
if (_currentTool == EditTool.Move)
{
// === ЛОГИКА ДЛЯ НАСТЕННЫХ ПРЕДМЕТОВ ===
if (_activeFurnitureScript.isWallObject)
{
if (Physics.Raycast(ray, out RaycastHit hit, 100f, wallLayer))
{
_activeFurniture.transform.position = hit.point;
// Магия: Поворачиваем объект "лицом" от стены
_activeFurniture.transform.rotation = Quaternion.LookRotation(hit.normal);
}
}
// === ЛОГИКА ДЛЯ НАПОЛЬНЫХ ПРЕДМЕТОВ (Старая) ===
else
{
if (Physics.Raycast(ray, out RaycastHit hit, 100f, floorLayer))
{
Vector3 currentPos = _activeFurniture.transform.position;
Vector3 targetPos = hit.point + _dragOffset;
targetPos.y = currentPos.y;
Vector3 moveDir = targetPos - currentPos;
float moveDist = moveDir.magnitude;
if (moveDist > 0.001f)
{
BoxCollider box = _activeFurniture.GetComponent<BoxCollider>();
if (box != null)
{
Vector3 center = _activeFurniture.transform.TransformPoint(box.center);
Vector3 halfExtents = Vector3.Scale(box.size, _activeFurniture.transform.lossyScale) * 0.49f;
if (Physics.BoxCast(center, halfExtents, moveDir.normalized, out RaycastHit wallHit, _activeFurniture.transform.rotation, moveDist, wallLayer))
{
float safeDist = Mathf.Max(0f, wallHit.distance - 0.01f);
Vector3 remainingMove = moveDir - (moveDir.normalized * safeDist);
Vector3 slideMove = Vector3.ProjectOnPlane(remainingMove, wallHit.normal);
if (slideMove.magnitude > 0.001f)
{
Vector3 newCenter = center + moveDir.normalized * safeDist;
if (Physics.BoxCast(newCenter, halfExtents, slideMove.normalized, out RaycastHit slideHit, _activeFurniture.transform.rotation, slideMove.magnitude, wallLayer))
{
slideMove = slideMove.normalized * Mathf.Max(0f, slideHit.distance - 0.01f);
}
}
targetPos = currentPos + (moveDir.normalized * safeDist) + slideMove;
}
}
}
targetPos.y = currentPos.y;
_activeFurniture.transform.position = targetPos;
}
}
}
else if (_currentTool == EditTool.Rotate)
{
float deltaX = Input.mousePosition.x - _lastInputPos.x;
// Настенные предметы крутим вокруг своей оси Z (по циферблату), а напольные - вокруг мировой Y
if (_activeFurnitureScript.isWallObject)
_activeFurniture.transform.Rotate(Vector3.forward, -deltaX * rotationSpeed * 0.2f, Space.Self);
else
_activeFurniture.transform.Rotate(Vector3.up, -deltaX * rotationSpeed * 0.2f, Space.World);
}
_lastInputPos = Input.mousePosition;
}
if (Input.GetMouseButtonUp(0) && _isInteracting) EndInteraction();
if (!_isInteracting) UpdateUIPosition();
}
private void TrySelectPlacedFurniture()
{
Ray ray = _cam.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit, 1000f, furnitureLayer, QueryTriggerInteraction.Collide))
{
FurnitureObject furnScript = hit.collider.GetComponentInParent<FurnitureObject>();
if (furnScript != null)
{
_activeFurniture = furnScript.gameObject;
_activeFurnitureScript = furnScript;
_activeFurnitureScript.SetEditMode(true);
_currentTool = EditTool.Move;
if (rotate90Button != null) rotate90Button.SetActive(false);
_isInteracting = false;
LockCamera(false);
UpdateUIPosition();
}
}
}
private void StartInteraction()
{
_isInteracting = true;
if (editPanel.activeSelf) editPanel.SetActive(false);
if (_currentTool == EditTool.Move) LockCamera(true);
}
private void EndInteraction()
{
_isInteracting = false;
UpdateUIPosition();
editPanel.SetActive(true);
if (_currentTool == EditTool.Move) LockCamera(false);
}
private void UpdateUIPosition()
{
Vector3 screenPos = _cam.WorldToScreenPoint(_activeFurniture.transform.position);
if (screenPos.z > 0)
{
if (!editPanel.activeSelf) editPanel.SetActive(true);
float yOffset = Screen.height * 0.15f;
float targetX = screenPos.x;
float targetY = screenPos.y + yOffset;
RectTransform rect = editPanel.GetComponent<RectTransform>();
if (rect != null)
{
float paddingX = (rect.rect.width / 2f) * editPanel.transform.lossyScale.x;
float paddingY = (rect.rect.height / 2f) * editPanel.transform.lossyScale.y;
targetX = Mathf.Clamp(targetX, paddingX, Screen.width - paddingX);
targetY = Mathf.Clamp(targetY, paddingY, Screen.height - paddingY);
}
editPanel.transform.position = new Vector3(targetX, targetY, editPanel.transform.position.z);
}
else if (editPanel.activeSelf) editPanel.SetActive(false);
}
void TryPlaceFurniture()
{
Ray ray = _cam.ScreenPointToRay(Input.mousePosition);
// Определяем, куда пускать луч при установке в зависимости от типа предмета
FurnitureObject prefabScript = currentPrefab.GetComponent<FurnitureObject>();
LayerMask targetLayer = prefabScript.isWallObject ? wallLayer : floorLayer;
if (Physics.Raycast(ray, out RaycastHit hit, 100f, targetLayer))
{
_activeFurniture = Instantiate(currentPrefab, hit.point, Quaternion.identity);
// Если это стена - сразу поворачиваем спиной к ней
if (prefabScript.isWallObject)
{
_activeFurniture.transform.rotation = Quaternion.LookRotation(hit.normal);
}
_activeFurnitureScript = _activeFurniture.GetComponent<FurnitureObject>();
_activeFurnitureScript.SetEditMode(true);
_currentTool = EditTool.Move;
if (rotate90Button != null) rotate90Button.SetActive(false);
currentPrefab = null;
_isInteracting = false;
LockCamera(false);
UpdateUIPosition();
}
}
public void Rotate90Degrees()
{
if (_activeFurniture != null)
{
if (_activeFurnitureScript.isWallObject)
{
// Настенные объекты поворачиваем по их локальной оси Z (как часы)
_activeFurniture.transform.Rotate(0, 0, 90f, Space.Self);
}
else
{
float currentY = _activeFurniture.transform.eulerAngles.y;
float snappedY = Mathf.Round(currentY / 90f) * 90f;
_activeFurniture.transform.rotation = Quaternion.Euler(0, snappedY + 90f, 0);
}
}
}
public void SelectMoveTool() { _currentTool = EditTool.Move; if (rotate90Button != null) rotate90Button.SetActive(false); LockCamera(false); }
public void SelectRotateTool() { _currentTool = EditTool.Rotate; if (rotate90Button != null) rotate90Button.SetActive(true); LockCamera(true); }
public void ConfirmPlacement()
{
if (_activeFurnitureScript != null && _activeFurnitureScript.IsPlacementValid)
{
_activeFurnitureScript.SetEditMode(false);
_activeFurniture = null;
_activeFurnitureScript = null;
editPanel.SetActive(false);
LockCamera(false);
}
}
public void CancelPlacement()
{
if (_activeFurniture != null)
{
Destroy(_activeFurniture);
_activeFurniture = null;
_activeFurnitureScript = null;
editPanel.SetActive(false);
LockCamera(false);
}
}
public void SelectFurnitureAndCloseShop(GameObject prefabToSelect)
{
currentPrefab = prefabToSelect;
shopPanel.SetActive(false);
}
private void LockCamera(bool isLocked) { if (cameraController != null) cameraController.enabled = !isLocked; }
private bool IsPointerOverUI()
{
if (EventSystem.current != null)
{
if (EventSystem.current.IsPointerOverGameObject()) return true;
if (Input.touchCount > 0 && EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId)) return true;
}
return false;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 37c5b010452efc242ae2c7e3114721a7
@@ -0,0 +1,75 @@
using UnityEngine;
public class FurnitureObject : MonoBehaviour
{
[Header("Тип объекта")]
public bool isWallObject = false; // ГАЛОЧКА: Это настенный предмет?
[Header("Настройки")]
public LayerMask obstacleLayers;
private int _obstaclesCount = 0;
public bool IsPlacementValid => _obstaclesCount == 0;
private GameObject _highlightBox;
private Material _highlightMaterial;
void Awake()
{
CreateHighlightBox();
}
private void CreateHighlightBox()
{
BoxCollider col = GetComponent<BoxCollider>();
if (col == null) return;
_highlightBox = GameObject.CreatePrimitive(PrimitiveType.Cube);
Destroy(_highlightBox.GetComponent<Collider>());
_highlightBox.transform.SetParent(transform);
_highlightBox.transform.localPosition = col.center;
_highlightBox.transform.localRotation = Quaternion.identity;
_highlightBox.transform.localScale = col.size;
_highlightMaterial = new Material(Shader.Find("Sprites/Default"));
_highlightBox.GetComponent<Renderer>().material = _highlightMaterial;
_highlightBox.SetActive(false);
}
public void SetEditMode(bool active)
{
if (_highlightBox != null)
{
_highlightBox.SetActive(active);
if (active) UpdateColor();
}
}
private void OnTriggerEnter(Collider other)
{
if (((1 << other.gameObject.layer) & obstacleLayers) != 0)
{
_obstaclesCount++;
UpdateColor();
}
}
private void OnTriggerExit(Collider other)
{
if (((1 << other.gameObject.layer) & obstacleLayers) != 0)
{
_obstaclesCount--;
UpdateColor();
}
}
private void UpdateColor()
{
if (_highlightMaterial != null)
{
Color targetColor = IsPlacementValid ? new Color(0, 1, 0, 0.4f) : new Color(1, 0, 0, 0.4f);
_highlightMaterial.color = targetColor;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7196b5f65c7bcd143b0f035424936bef
@@ -0,0 +1,115 @@
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class PillarData
{
public GameObject pillarObject;
public GameObject connectedWall1;
public GameObject connectedWall2;
}
public class RoomVisibilityController : MonoBehaviour
{
[Header("Центр комнаты")]
public Transform roomCenter;
[Header("Стены (Просто перетащите 4 стены)")]
public GameObject[] walls;
[Header("Столбики")]
public PillarData[] pillars;
[Header("Настройки видимости")]
[Range(-0.5f, 0.5f)]
public float hideThreshold = 0.1f;
private Camera _mainCamera;
private Dictionary<GameObject, bool> _wallHiddenStates = new Dictionary<GameObject, bool>();
// Кэшируем Renderer'ы для оптимизации (чтобы не делать GetComponent каждый кадр)
private Dictionary<GameObject, Renderer[]> _objectRenderers = new Dictionary<GameObject, Renderer[]>();
void Start()
{
_mainCamera = Camera.main;
// При старте игры находим и запоминаем все Renderer'ы
foreach (var wall in walls) { CacheRenderers(wall); }
foreach (var pillar in pillars) { CacheRenderers(pillar.pillarObject); }
}
private void CacheRenderers(GameObject obj)
{
if (obj != null && !_objectRenderers.ContainsKey(obj))
{
_objectRenderers[obj] = obj.GetComponentsInChildren<Renderer>();
}
}
void LateUpdate()
{
if (_mainCamera == null || roomCenter == null) return;
Vector3 dirToCamera = _mainCamera.transform.position - roomCenter.position;
dirToCamera.y = 0; // Игнорируем высоту
// 1. СТЕНЫ
foreach (var wall in walls)
{
if (wall == null) continue;
Vector3 targetPos = GetRealCenter(wall);
Vector3 dirToWall = targetPos - roomCenter.position;
dirToWall.y = 0;
bool isHidden = Vector3.Dot(dirToCamera.normalized, dirToWall.normalized) > hideThreshold;
// Включаем или выключаем графику стены моментально
SetVisibility(wall, !isHidden);
_wallHiddenStates[wall] = isHidden;
Debug.DrawLine(roomCenter.position, targetPos, isHidden ? Color.red : Color.green);
}
// 2. СТОЛБИКИ
foreach (var pillar in pillars)
{
if (pillar.pillarObject == null || pillar.connectedWall1 == null || pillar.connectedWall2 == null)
continue;
bool isWall1Hidden = _wallHiddenStates.ContainsKey(pillar.connectedWall1) && _wallHiddenStates[pillar.connectedWall1];
bool isWall2Hidden = _wallHiddenStates.ContainsKey(pillar.connectedWall2) && _wallHiddenStates[pillar.connectedWall2];
// Прячем столбик только если ОБЕ подключенные стены спрятаны
bool shouldHidePillar = isWall1Hidden && isWall2Hidden;
SetVisibility(pillar.pillarObject, !shouldHidePillar);
}
}
// Метод для быстрого включения/выключения отрисовки объекта
private void SetVisibility(GameObject obj, bool isVisible)
{
if (obj == null || !_objectRenderers.ContainsKey(obj)) return;
Renderer[] renderers = _objectRenderers[obj];
foreach (Renderer r in renderers)
{
if (r.enabled != isVisible)
{
r.enabled = isVisible;
}
}
}
private Vector3 GetRealCenter(GameObject obj)
{
Renderer r = obj.GetComponentInChildren<Renderer>();
if (r != null)
{
return r.bounds.center;
}
return obj.transform.position;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 95bc6e27b7d341a4493014fef624b5eb
@@ -0,0 +1,52 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI; // Обязательно добавляем для работы с интерфейсом
// Этот класс - наша "карточка товара". Он хранит иконку и 3D-модель.
[System.Serializable] // Позволяет отображать этот класс в инспекторе Unity
public class FurnitureItem
{
public string itemName; // Название (просто для вашего удобства в инспекторе)
public Sprite icon; // Иконка для магазина
public GameObject prefab; // 3D-модель для установки
}
public class ShopManager : MonoBehaviour
{
[Header("Связи")]
public FurnitureController builder; // Ссылка на ваш скрипт строительства
public GameObject buttonTemplate; // Наш префаб кнопки магазина
public Transform contentPanel; // Тот самый объект Content с Grid Layout Group
[Header("Каталог мебели")]
public List<FurnitureItem> items; // Список всей мебели в игре
void Start()
{
// Как только игра запускается, генерируем магазин
GenerateShop();
}
void GenerateShop()
{
// Проходимся по каждому предмету в нашем каталоге
foreach (FurnitureItem item in items)
{
// 1. Создаем копию шаблона кнопки внутри панели Content
GameObject newButton = Instantiate(buttonTemplate, contentPanel);
// 2. Находим компонент Image на этой кнопке и меняем картинку на нашу иконку
newButton.GetComponent<Image>().sprite = item.icon;
// 3. Находим компонент Button, чтобы настроить клик
Button btn = newButton.GetComponent<Button>();
// Сохраняем префаб в локальную переменную (это важно для правильной работы кода)
GameObject prefabToSelect = item.prefab;
// 4. Программно добавляем действие при клике (то же самое, что плюсик в инспекторе)
// Мы вызываем метод из вашего прошлого скрипта!
btn.onClick.AddListener(() => builder.SelectFurnitureAndCloseShop(prefabToSelect));
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 07c4fd35416ae7d4aa742d551654809f
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 1b6aa5d81f54996409a3f8ce4bcabb8d
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: e725961d934232643a99d6378da89d17
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
using UnityEngine;
public abstract class BonusEffect : ScriptableObject
{
[Tooltip("Длительность бонуса в секундах")]
public float duration = 10f;
public abstract void Activate(GameObject player);
public abstract void Deactivate(GameObject player);
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: bd9853d2913c2c949bbc8a06d0b9ee48
@@ -0,0 +1,82 @@
using System.Collections;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class BonusManager : MonoBehaviour
{
public static BonusManager Instance { get; private set; }
[Header("UI Элементы")]
public Image bonusIcon;
public TextMeshProUGUI bonusTimerText;
private BonusEffect _activeBonus;
private float _timer;
private GameObject _player;
private int _lastDisplayedTime = -1;
void Awake()
{
if (Instance == null) Instance = this;
else Destroy(gameObject);
}
void Start()
{
_player = GameObject.FindGameObjectWithTag("Player");
bonusIcon.gameObject.SetActive(false);
bonusTimerText.gameObject.SetActive(false);
}
void Update()
{
if (_activeBonus != null)
{
_timer -= Time.deltaTime;
if (_timer <= 0)
{
DeactivateBonus();
}
else
{
int secondsLeft = Mathf.CeilToInt(_timer);
if (secondsLeft != _lastDisplayedTime)
{
_lastDisplayedTime = secondsLeft;
bonusTimerText.text = secondsLeft.ToString();
}
}
}
}
public void ActivateBonus(BonusEffect bonus)
{
if (_activeBonus != null)
{
DeactivateBonus();
}
_activeBonus = bonus;
_timer = _activeBonus.duration;
_lastDisplayedTime = -1;
_activeBonus.Activate(_player);
bonusIcon.gameObject.SetActive(true);
bonusTimerText.gameObject.SetActive(true);
}
private void DeactivateBonus()
{
if (_activeBonus != null && _player != null)
{
_activeBonus.Deactivate(_player);
}
_activeBonus = null;
_timer = 0;
bonusIcon.gameObject.SetActive(false);
bonusTimerText.gameObject.SetActive(false);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: b01c170304735a241bc36fff9ab0dd50
@@ -0,0 +1,35 @@
using UnityEngine;
public class BonusPickup : MonoBehaviour
{
public BonusEffect bonusEffect;
public float rotationSpeed = 100f;
private GameObject _originalPrefab;
public void Init(GameObject prefab)
{
_originalPrefab = prefab;
}
void Update()
{
transform.Rotate(Vector3.up, rotationSpeed * Time.deltaTime);
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
if (BonusManager.Instance != null && bonusEffect != null)
{
BonusManager.Instance.ActivateBonus(bonusEffect);
Debug.Log("бонус подобран");
}
if (_originalPrefab != null)
SimpleObjectPool.Instance.ReturnToPool(_originalPrefab, gameObject);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: b542a0080e584884f8d0bc2ae46aaf59
@@ -0,0 +1,49 @@
using System.Collections;
using UnityEngine;
public class BonusSpawner : MonoBehaviour
{
[Header("Настройки спавна")]
public GameObject[] bonusPrefabs;
[Tooltip("Минимальное и максимальное время между спавнами бонусов")]
public Vector2 spawnInterval = new Vector2(10f, 20f);
[Tooltip("Как далеко впереди игрока спавнить бонус")]
public float spawnDistance = 100f;
private Transform _playerTransform;
void Start()
{
StartCoroutine(SpawnBonusRoutine());
}
IEnumerator SpawnBonusRoutine()
{
while (true)
{
float waitTime = Random.Range(spawnInterval.x, spawnInterval.y);
yield return new WaitForSeconds(waitTime);
if (bonusPrefabs.Length == 0 || RoadManager.Instance == null || RoadManager.Instance.playerTransform == null)
{
continue;
}
float spawnX = RoadManager.Instance.GetRandomLaneX();
float spawnZ = RoadManager.Instance.playerTransform.position.z + spawnDistance;
Vector3 spawnPosition = new Vector3(spawnX, 0.5f, spawnZ);
GameObject bonusPrefab = bonusPrefabs[Random.Range(0, bonusPrefabs.Length)];
GameObject bonus = SimpleObjectPool.Instance.Get(bonusPrefab, spawnPosition, Quaternion.identity);
BonusPickup pickup = bonus.GetComponent<BonusPickup>();
if (pickup != null)
{
pickup.Init(bonusPrefab);
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 095f133ed0b1459449748ef072132e77
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: f045b7417984498aaf503eb5afb7c313
timeCreated: 1783938890
@@ -0,0 +1,22 @@
using UnityEngine;
[CreateAssetMenu(fileName = "X2Bonus", menuName = "Bonuses/x2 Bonus")]
public class X2Bonus : BonusEffect
{
public override void Activate(GameObject player)
{
if (GameManager.Instance != null)
{
GameManager.Instance.SetScoreMultiplier(2);
}
}
public override void Deactivate(GameObject player)
{
if (GameManager.Instance != null)
{
GameManager.Instance.SetScoreMultiplier(1);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 5dc2ead9299e0bc499c6104712ece1d0
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: dca72d0db8e274e4ba3a76468d18e939
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,45 @@
using System.Collections;
using Boxes;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class Box : MonoBehaviour
{
public BoxData boxData;
private Coroutine _lifetimeCoroutine;
public void Init(BoxData data)
{
boxData = data;
if (_lifetimeCoroutine != null) StopCoroutine(_lifetimeCoroutine);
_lifetimeCoroutine = StartCoroutine(LifetimeRoutine());
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Player"))
{
if (boxData != null)
{
GameEvents.OnBoxCollected?.Invoke(boxData);
}
CollectAndReturn();
}
}
IEnumerator LifetimeRoutine()
{
yield return new WaitForSeconds(15f);
CollectAndReturn();
}
private void CollectAndReturn()
{
if (_lifetimeCoroutine != null) StopCoroutine(_lifetimeCoroutine);
if (boxData != null && boxData.boxPrefab != null)
{
SimpleObjectPool.Instance.ReturnToPool(boxData.boxPrefab, gameObject);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 004b1fc0980fdb241b3fad09064f5b2a
@@ -0,0 +1,29 @@
using UnityEngine;
namespace Boxes
{
[CreateAssetMenu(fileName = "NewBoxData", menuName = "Boxes/Box Data")]
public class BoxData : ScriptableObject
{
public enum BoxEffectType
{
AddScore,
LoseScore,
SpecialFurniture
}
[Header("Игровые параметры")]
public BoxEffectType effectType = BoxEffectType.AddScore;
[Tooltip("Значение эффекта (очки или секунды)")]
public float effectValue = 1;
[Tooltip("Вес спавна")]
public float spawnWeight = 10f;
[Header("Визуальное представление")]
public GameObject boxPrefab;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a6a293f7fca35fc43ac2f3ebcb0954ce
@@ -0,0 +1,31 @@
using UnityEngine;
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
public Transform target;
private Vector3 _offset;
void Start()
{
if (target != null)
{
_offset = transform.position - target.position;
}
else
{
Debug.LogError("Камера: не назначен объект Target!");
}
}
void LateUpdate()
{
if (target != null)
{
transform.position = target.position + _offset;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 6315ff2434746fd4e910402d25ecf1ef
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: b4055b01bd96cdc4284d0f854ea1cc5f
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: fd21099208822254b8bb1257638791dd
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,15 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 5dc2ead9299e0bc499c6104712ece1d0, type: 3}
m_Name: X2_Bonus_Data
m_EditorClassIdentifier: Assembly-CSharp::X2Bonus
duration: 10
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 8e5c8fbfcc85bfd4fbc7f91cbf428dd9
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 3c97daf6ae6c71342988de3835739603
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,17 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: a6a293f7fca35fc43ac2f3ebcb0954ce, type: 3}
m_Name: Default_Box_Data
m_EditorClassIdentifier: Assembly-CSharp::BoxData
scoreValue: 1
spawnWeight: 10
boxPrefab: {fileID: 6275688211726782222, guid: d8a904c3247993448af892890944e360, type: 3}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 8158ddabab3735143a9847f4d160add5
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,18 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: a6a293f7fca35fc43ac2f3ebcb0954ce, type: 3}
m_Name: Furniture_Box
m_EditorClassIdentifier: Assembly-CSharp::Boxes.BoxData
effectType: 2
effectValue: 0
spawnWeight: 1
boxPrefab: {fileID: 8149457572473518044, guid: 66f5766a1cb106a408bd127d1433c837, type: 3}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 240949ca7ac904c45a2b93cc3172efce
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,18 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: a6a293f7fca35fc43ac2f3ebcb0954ce, type: 3}
m_Name: Golden_Box_Data
m_EditorClassIdentifier: Assembly-CSharp::BoxData
effectType: 0
effectValue: 3
spawnWeight: 1
boxPrefab: {fileID: 4495264409879407278, guid: 4004248628f71f9439bd61c6bdba5ab4, type: 3}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: df5fdd65860534548b58b238b0dd79dc
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,18 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: a6a293f7fca35fc43ac2f3ebcb0954ce, type: 3}
m_Name: Penalty_Box
m_EditorClassIdentifier: Assembly-CSharp::BoxData
effectType: 1
effectValue: 5
spawnWeight: 3
boxPrefab: {fileID: 7341766889371574851, guid: 31ae8bc5115ff86408099ffb61b114c3, type: 3}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 974f6de7bb0cb774d9e8a78dddca9be9
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,12 @@
using System;
using Boxes;
public static class GameEvents
{
public static Action<BoxData> OnBoxCollected;
public static Action OnPlayerDied;
public static Action OnBoxAddedToTruck;
public static Action OnBoxLostFromTruck;
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: c17ab1cd06006d44f83f59933ef9c5c5
@@ -0,0 +1,130 @@
using Boxes;
using UnityEngine;
using UnityEngine.SceneManagement;
using TMPro;
public class GameManager : MonoBehaviour
{
[Header("Ссылки на UI")]
public TextMeshProUGUI timerText;
public TextMeshProUGUI boxesText;
public GameObject endGameScreen;
public TextMeshProUGUI finalScoreText;
private int _boxesCollected;
private float _timeAlive;
private bool _isPlaying = true;
private int _scoreMultiplier = 1;
public static GameManager Instance { get; private set; }
void Awake()
{
if (Instance == null) Instance = this;
else Destroy(gameObject);
}
private void OnEnable()
{
GameEvents.OnBoxCollected += OnBoxCollected;
GameEvents.OnPlayerDied += EndGame;
}
private void OnDisable()
{
GameEvents.OnBoxCollected -= OnBoxCollected;
GameEvents.OnPlayerDied -= EndGame;
}
void Start()
{
_scoreMultiplier = 1;
_timeAlive = 0f;
_isPlaying = true;
_boxesCollected = 0;
if (endGameScreen != null) endGameScreen.SetActive(false);
Time.timeScale = 1f;
UpdateUI();
}
void Update()
{
if (!_isPlaying) return;
_timeAlive += Time.deltaTime;
UpdateUI();
}
private void OnBoxCollected(BoxData boxData)
{
if (!_isPlaying) return;
switch (boxData.effectType)
{
case BoxData.BoxEffectType.AddScore:
int addAmount = (int)boxData.effectValue * _scoreMultiplier;
for(int i = 0; i < addAmount; i++)
{
_boxesCollected++;
GameEvents.OnBoxAddedToTruck?.Invoke();
}
break;
case BoxData.BoxEffectType.LoseScore:
int loseAmount = (int)boxData.effectValue;
for(int i = 0; i < loseAmount; i++)
{
if (_boxesCollected > 0)
{
_boxesCollected--;
GameEvents.OnBoxLostFromTruck?.Invoke();
}
}
break;
case BoxData.BoxEffectType.SpecialFurniture:
Debug.Log("Собрана мебель!");
break;
}
UpdateUI();
}
public void SetScoreMultiplier(int multiplier)
{
_scoreMultiplier = multiplier;
}
void UpdateUI()
{
if (timerText != null)
{
timerText.text = $"Время: {Mathf.FloorToInt(_timeAlive / 60):00}:{Mathf.FloorToInt(_timeAlive % 60):00}";
}
if (boxesText != null)
{
boxesText.text = $"Собрано: {_boxesCollected}";
}
}
void EndGame()
{
if (!_isPlaying) return;
_isPlaying = false;
if (endGameScreen != null) endGameScreen.SetActive(true);
if (finalScoreText != null)
{
finalScoreText.text = $"Вы собрали: {_boxesCollected} коробок!";
}
}
public void RestartGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 6a279a612ca915348b6fec0a78edca77
@@ -0,0 +1,37 @@
using Obstacle;
using UnityEngine;
using Player;
public class GameProgression : MonoBehaviour
{
[Header("Ссылки на системы")]
public PlayerCarController player;
public ObstacleSpawner spawner;
public VanController van;
[Header("Графики сложности (Ось X - секунды игры)")]
[Tooltip("Как растет скорость машины")]
public AnimationCurve speedCurve = AnimationCurve.Linear(0, 20, 120, 50);
[Tooltip("Задержка между спавном. Чем ниже график, тем плотнее поток машин")]
public AnimationCurve spawnIntervalCurve = AnimationCurve.Linear(0, 1.5f, 120, 0.4f);
[Tooltip("Шанс появления препятствий вместо авто ")]
public AnimationCurve obstacleChanceCurve = AnimationCurve.Linear(0, 0.1f, 120, 0.5f);
private float _timeAlive;
void Update()
{
// Считаем время заезда
_timeAlive += Time.deltaTime;
float currentSpeed = speedCurve.Evaluate(_timeAlive);
if (player != null) player.forwardSpeed = currentSpeed;
if (van != null) van.forwardSpeed = currentSpeed;
spawner.currentSpawnInterval = spawnIntervalCurve.Evaluate(_timeAlive);
spawner.currentObstacleChance = obstacleChanceCurve.Evaluate(_timeAlive);
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 9cf4597c514b4decb51aab826406f120
timeCreated: 1783938468
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 4d9fde0ee5b6495494318f116c5a093e
timeCreated: 1783938401
@@ -0,0 +1,46 @@
using System.Collections.Generic;
using UnityEngine;
public class SimpleObjectPool : MonoBehaviour
{
public static SimpleObjectPool Instance { get; private set; }
private Dictionary<GameObject, Queue<GameObject>> _pools = new Dictionary<GameObject, Queue<GameObject>>();
void Awake()
{
if (Instance == null) Instance = this;
else Destroy(gameObject);
}
public GameObject Get(GameObject prefab, Vector3 position, Quaternion rotation)
{
if (!_pools.ContainsKey(prefab))
{
_pools.Add(prefab, new Queue<GameObject>());
}
GameObject obj;
if (_pools[prefab].Count > 0)
{
obj = _pools[prefab].Dequeue();
obj.transform.position = position;
obj.transform.rotation = rotation;
obj.SetActive(true);
}
else
{
obj = Instantiate(prefab, position, rotation);
}
return obj;
}
public void ReturnToPool(GameObject prefab, GameObject obj)
{
obj.SetActive(false);
if (_pools.ContainsKey(prefab))
{
_pools[prefab].Enqueue(obj);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: bb56a90f04ee457fbd31022c77a40db6
timeCreated: 1783605341
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 17e405aa38144dd2aa3e67ed3fb6c400
timeCreated: 1783938258
@@ -0,0 +1,80 @@
using UnityEngine;
namespace Obstacle
{
public class ObstacleSpawner : MonoBehaviour
{
[Header("Настройки спавна")]
public float spawnDistance = 150f;
[Header("Статические препятствия")]
public GameObject[] staticObstaclePrefabs;
[HideInInspector] public float currentSpawnInterval = 1f;
[HideInInspector] public float currentObstacleChance = 0.2f;
private Transform _playerTransform;
private RoadManager _roadManager;
private float _timer;
void Start()
{
_playerTransform = GameObject.FindGameObjectWithTag("Player").transform;
_roadManager = RoadManager.Instance;
}
void Update()
{
if (_playerTransform == null) return;
_timer += Time.deltaTime;
if (_timer >= currentSpawnInterval)
{
_timer = 0f;
SpawnObject();
}
}
private void SpawnObject()
{
float spawnX = _roadManager.GetRandomLaneX();
float spawnZ = _playerTransform.position.z + spawnDistance;
Vector3 spawnPos = new Vector3(spawnX, 0f, spawnZ);
if (staticObstaclePrefabs.Length > 0 && Random.value < currentObstacleChance)
{
GameObject prefab = staticObstaclePrefabs[Random.Range(0, staticObstaclePrefabs.Length)];
spawnPos.y = prefab.transform.position.y;
GameObject obstacle = SimpleObjectPool.Instance.Get(prefab, spawnPos, prefab.transform.rotation);
StaticObstacle obsScript = obstacle.GetComponent<StaticObstacle>();
if (obsScript == null) obsScript = obstacle.AddComponent<StaticObstacle>();
obsScript.Init(_playerTransform, prefab);
}
else
{
TrafficCar car = TrafficPool.Instance.GetCar();
if (car != null)
{
car.Init(_playerTransform, _roadManager);
spawnPos.y = car.transform.position.y;
car.SetStartPosition(spawnPos);
car.transform.rotation = Quaternion.Euler(0, spawnX < 0 ? 180 : 0, 0);
if (Random.value < 0.5f)
car.SetBehavior(RandomLaneChangingBehavior.Instance);
else
car.SetBehavior(SimpleLaneFollowingBehavior.Instance);
car.gameObject.SetActive(true);
}
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 1104895103114f3cb12ec5473b02dd34
timeCreated: 1783939549
@@ -0,0 +1,27 @@
using UnityEngine;
namespace Obstacle
{
public class StaticObstacle : MonoBehaviour
{
public float despawnDistance = 20f;
private Transform _player;
private GameObject _originalPrefab;
public void Init(Transform player, GameObject prefab)
{
_player = player;
_originalPrefab = prefab;
}
void Update()
{
if (_player != null && transform.position.z < _player.position.z - despawnDistance)
{
SimpleObjectPool.Instance.ReturnToPool(_originalPrefab, gameObject);
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 25f81066c3274a6aa3ef2bc41a224413
timeCreated: 1783938281
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: a3b8c1914efa48a19d96805c360043e2
timeCreated: 1783691441
@@ -0,0 +1,89 @@
using Obstacle;
using UnityEngine;
namespace Player
{
[RequireComponent(typeof(Rigidbody))]
public class PlayerCarController : MonoBehaviour
{
[Header("Скорость движения")]
public float forwardSpeed = 20f;
public float sideSpeed = 15f;
public float horizontalLimit = 4.5f;
[Header("Управление")]
public float swipeSensitivity = 1.5f;
[Header("Визуальный наклон ")]
[Tooltip("На сколько градусов поворачивается нос машины при перестроении")]
public float maxTiltAngle = 15f;
[Tooltip("Как быстро машина выравнивается обратно")]
public float tiltSpeed = 10f;
private Rigidbody _rb;
private bool _isAlive = true;
private float _targetX;
private Vector2 _lastInputPosition;
void Start()
{
_rb = GetComponent<Rigidbody>();
_isAlive = true;
_targetX = transform.position.x;
}
void Update()
{
if (!_isAlive) return;
if (Input.GetMouseButtonDown(0))
{
_lastInputPosition = Input.mousePosition;
}
else if (Input.GetMouseButton(0))
{
float deltaX = Input.mousePosition.x - _lastInputPosition.x;
_lastInputPosition = Input.mousePosition;
// Сдвигаем целевую точку X
_targetX += (deltaX / Screen.width) * swipeSensitivity * 10f;
_targetX = Mathf.Clamp(_targetX, -horizontalLimit, horizontalLimit);
}
}
void FixedUpdate()
{
if (!_isAlive) return;
Vector3 currentPos = _rb.position;
float newX = Mathf.MoveTowards(currentPos.x, _targetX, sideSpeed * Time.fixedDeltaTime);
Vector3 moveTarget = new Vector3(newX, currentPos.y, currentPos.z + forwardSpeed * Time.fixedDeltaTime);
_rb.MovePosition(moveTarget);
float deltaX = newX - currentPos.x;
float direction = deltaX / (sideSpeed * Time.fixedDeltaTime);
// Поворачиваем нос машины в сторону движения
Quaternion targetRotation = Quaternion.Euler(0, direction * maxTiltAngle, 0);
_rb.MoveRotation(Quaternion.Lerp(_rb.rotation, targetRotation, tiltSpeed * Time.fixedDeltaTime));
}
private void OnCollisionEnter(Collision collision)
{
if (!_isAlive) return;
if (collision.gameObject.GetComponent<TrafficCar>() != null ||
collision.gameObject.GetComponent<StaticObstacle>() != null)
{
_isAlive = false;
GameEvents.OnPlayerDied?.Invoke();
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 087244143aa340d2a05c776db44651bd
timeCreated: 1783691666
@@ -0,0 +1,156 @@
namespace Player
{
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TruckBedVisuals : MonoBehaviour
{
[Header("Настройки кузова")]
public Transform bedStartPoint;
public GameObject visualBoxPrefab;
[Header("Сетка укладки")]
public int columns = 3;
public int rows = 3;
[Header("Размеры и отступы ")]
public bool uniformScale = true;
public Vector3 boxSize = new Vector3(1f, 1f, 1f);
public Vector3 boxPadding = new Vector3(0.05f, 0.05f, 0.05f);
[Header("Отрисовка в редакторе")]
public int gizmoPreviewLayers = 3;
[Header("Физика выпадения")]
public float dropUpForce = 5f;
public float dropBackForce = 15f;
public float dropTorque = 10f;
private Stack<GameObject> _stackedBoxes = new Stack<GameObject>();
private Collider _carCollider;
private void OnValidate()
{
if (uniformScale)
{
boxSize.y = boxSize.x;
boxSize.z = boxSize.x;
boxPadding.y = boxPadding.x;
boxPadding.z = boxPadding.x;
}
}
void Awake()
{
_carCollider = GetComponent<Collider>();
}
private void OnEnable()
{
GameEvents.OnBoxAddedToTruck += AddBox;
GameEvents.OnBoxLostFromTruck += DropBox;
}
private void OnDisable()
{
GameEvents.OnBoxAddedToTruck -= AddBox;
GameEvents.OnBoxLostFromTruck -= DropBox;
}
private void OnDrawGizmos()
{
if (bedStartPoint == null) return;
Gizmos.color = new Color(0f, 1f, 0f, 0.5f);
Vector3 step = boxSize + boxPadding;
// Сохраняем старую матрицу и применяем трансформацию якоря кузова.
// Теперь сетка будет крутиться и двигаться вместе с машиной!
Matrix4x4 oldMatrix = Gizmos.matrix;
Gizmos.matrix = bedStartPoint.localToWorldMatrix;
for (int layer = 0; layer < gizmoPreviewLayers; layer++)
{
for (int x = 0; x < columns; x++)
{
for (int z = 0; z < rows; z++)
{
Vector3 boxCenter = new Vector3(x * step.x, layer * step.y, -z * step.z);
Gizmos.DrawWireCube(boxCenter, boxSize);
}
}
}
Gizmos.matrix = oldMatrix;
}
private void AddBox()
{
if (visualBoxPrefab == null || bedStartPoint == null) return;
int index = _stackedBoxes.Count;
int layer = index / (columns * rows);
int indexInLayer = index % (columns * rows);
int x = indexInLayer % columns;
int z = indexInLayer / columns;
Vector3 step = boxSize + boxPadding;
Vector3 localPos = new Vector3(x * step.x, layer * step.y, -z * step.z);
GameObject newBox = SimpleObjectPool.Instance.Get(visualBoxPrefab, bedStartPoint.position, bedStartPoint.rotation);
newBox.transform.SetParent(bedStartPoint);
newBox.transform.localPosition = localPos;
newBox.transform.localRotation = Quaternion.identity;
newBox.transform.localScale = boxSize;
Rigidbody rb = newBox.GetComponent<Rigidbody>();
if (rb != null) rb.isKinematic = true;
Collider coll = newBox.GetComponent<Collider>();
if (coll != null) coll.enabled = false;
_stackedBoxes.Push(newBox);
}
private void DropBox()
{
if (_stackedBoxes.Count == 0) return;
GameObject boxToDrop = _stackedBoxes.Pop();
boxToDrop.transform.SetParent(null);
Collider coll = boxToDrop.GetComponent<Collider>();
if (coll != null)
{
coll.enabled = true;
if (_carCollider != null) Physics.IgnoreCollision(coll, _carCollider);
}
Rigidbody rb = boxToDrop.GetComponent<Rigidbody>();
if (rb != null)
{
rb.isKinematic = false;
Rigidbody carRb = GetComponent<Rigidbody>();
if (carRb != null) rb.linearVelocity = carRb.linearVelocity;
Vector3 force = transform.up * dropUpForce - transform.forward * dropBackForce;
rb.AddForce(force, ForceMode.Impulse);
rb.AddTorque(Random.insideUnitSphere * dropTorque, ForceMode.Impulse);
}
StartCoroutine(ReturnBoxToPool(boxToDrop, 3f));
}
IEnumerator ReturnBoxToPool(GameObject box, float delay)
{
yield return new WaitForSeconds(delay);
SimpleObjectPool.Instance.ReturnToPool(visualBoxPrefab, box);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: dc39e6231af5447ca46f490d2aba601a
timeCreated: 1783765082
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e82ad7a78b1248d181a85feb7f7bd45f
timeCreated: 1783939713
@@ -0,0 +1,85 @@
using System.Collections.Generic;
using UnityEngine;
public class RoadManager : MonoBehaviour
{
public static RoadManager Instance { get; private set; }
public GameObject roadPrefab;
public Transform playerTransform;
public int initialRoads = 5;
public float roadLength = 30.0f;
[Header("Настройки удаления")]
public float safeDistanceBehind = 60f;
[Header("Координаты полос")]
public float[] laneXPositions = new float[] { -3.5f, 0f, 3.5f };
private Queue<GameObject> _activeRoads = new Queue<GameObject>();
private float _spawnZ = 0;
private void Awake()
{
if (Instance == null) Instance = this;
else Destroy(gameObject);
}
void Start()
{
if (playerTransform == null) return;
for (int i = 0; i < initialRoads; i++)
{
SpawnRoad();
}
}
void Update()
{
if (playerTransform == null) return;
float oldestRoadZ = _spawnZ - (_activeRoads.Count * roadLength);
if (playerTransform.position.z - oldestRoadZ > safeDistanceBehind)
{
SpawnRoad();
RecycleOldestRoad();
}
}
private void SpawnRoad()
{
GameObject road = SimpleObjectPool.Instance.Get(roadPrefab, Vector3.forward * _spawnZ, Quaternion.identity);
_activeRoads.Enqueue(road);
_spawnZ += roadLength;
}
private void RecycleOldestRoad()
{
if (_activeRoads.Count > 0)
{
GameObject oldRoad = _activeRoads.Dequeue();
SimpleObjectPool.Instance.ReturnToPool(roadPrefab, oldRoad);
}
}
public float GetRandomLaneX()
{
return laneXPositions[Random.Range(0, laneXPositions.Length)];
}
public float GetRandomSideLaneX(float currentX)
{
if (currentX < 0)
{
return laneXPositions[Random.Range(0, 2)];
}
else
{
return laneXPositions[Random.Range(2, 4)];
}
}
public int GetLanesCount() => laneXPositions.Length;
public float GetLaneX(int index) => laneXPositions[Mathf.Clamp(index, 0, laneXPositions.Length - 1)];
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ee30a387b9bb49647acee0eb955b6859
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d07bc7907f6240b4185238d1bfd2a0f5
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 705e158c647b33948a0f63c90bd5249a
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,7 @@
using UnityEngine;
public interface ICarBehavior
{
void UpdateBehavior(TrafficCar car);
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ff21a0b6c41511c48a7acdd901df6f4c
@@ -0,0 +1,37 @@
using UnityEngine;
// RandomLaneChangingBehavior.cs
using UnityEngine;
public class RandomLaneChangingBehavior : ICarBehavior
{
public static readonly RandomLaneChangingBehavior Instance = new RandomLaneChangingBehavior();
private readonly float _minChangeTime = 2f;
private readonly float _maxChangeTime = 5f;
public void UpdateBehavior(TrafficCar car)
{
car.transform.Translate(Vector3.forward * car.forwardSpeed * Time.deltaTime);
Vector3 newPos = car.transform.position;
newPos.x = Mathf.Lerp(newPos.x, car.TargetX, Time.deltaTime * car.laneChangeSpeed);
car.transform.position = newPos;
car.laneChangeTimer -= Time.deltaTime;
if (car.laneChangeTimer <= 0)
{
ChangeLane(car);
car.laneChangeTimer = Random.Range(_minChangeTime, _maxChangeTime);
}
}
private void ChangeLane(TrafficCar car)
{
if (car.roadManager != null)
{
car.TargetX = car.roadManager.GetRandomSideLaneX(car.TargetX);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 2f6a8c41c37d4724789bef430520c4a0
@@ -0,0 +1,17 @@
using UnityEngine;
public class SimpleLaneFollowingBehavior : ICarBehavior
{
public static readonly SimpleLaneFollowingBehavior Instance = new SimpleLaneFollowingBehavior();
public void UpdateBehavior(TrafficCar car)
{
car.transform.Translate(Vector3.forward * car.forwardSpeed * Time.deltaTime);
Vector3 newPos = car.transform.position;
newPos.x = Mathf.Lerp(newPos.x, car.TargetX, Time.deltaTime * car.laneChangeSpeed);
car.transform.position = newPos;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 4a155a999602a244b88e3287b6a072ab
@@ -0,0 +1,47 @@
using UnityEngine;
public class TrafficCar : MonoBehaviour
{
[Header("Движение")]
public float forwardSpeed = 8f;
public float laneChangeSpeed = 5f;
public float despawnDistanceBehindPlayer = 30f;
[HideInInspector] public GameObject originalPrefab;
[HideInInspector] public RoadManager roadManager;
[HideInInspector] public float laneChangeTimer;
public float TargetX { get; set; }
private Transform _playerTransform;
private ICarBehavior _behavior;
public void Init( Transform _player, RoadManager _roadManager)
{
_playerTransform = _player;
roadManager = _roadManager;
laneChangeTimer = Random.Range(2f, 5f);
}
void Update()
{
_behavior?.UpdateBehavior(this);
if (_playerTransform != null && transform.position.z < _playerTransform.position.z - despawnDistanceBehindPlayer)
{
TrafficPool.Instance.ReturnCar(this);
}
}
public void SetBehavior(ICarBehavior newBehavior)
{
_behavior = newBehavior;
}
public void SetStartPosition(Vector3 position)
{
transform.position = position;
TargetX = position.x;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: d5416a1a260deaa4881b833b9c43fdd0
@@ -0,0 +1,77 @@
using System.Collections.Generic;
using UnityEngine;
public class TrafficPool : MonoBehaviour
{
public static TrafficPool Instance { get; private set; }
[System.Serializable]
public class PoolEntry
{
public GameObject prefab;
public int size;
}
[Header("Настройки пула")]
public List<PoolEntry> poolEntries;
private Dictionary<GameObject, Queue<TrafficCar>> _poolDictionary;
void Awake()
{
if (Instance == null) Instance = this;
else Destroy(gameObject);
_poolDictionary = new Dictionary<GameObject, Queue<TrafficCar>>();
foreach (var entry in poolEntries)
{
Queue<TrafficCar> objectPool = new Queue<TrafficCar>();
for (int i = 0; i < entry.size; i++)
{
GameObject car = Instantiate(entry.prefab, transform);
car.transform.rotation = Quaternion.identity;
car.SetActive(false);
TrafficCar carComponent = car.GetComponent<TrafficCar>();
carComponent.originalPrefab = entry.prefab;
objectPool.Enqueue(carComponent);
}
_poolDictionary.Add(entry.prefab, objectPool);
}
}
public TrafficCar GetCar()
{
if (poolEntries.Count == 0) return null;
PoolEntry randomEntry = poolEntries[Random.Range(0, poolEntries.Count)];
Queue<TrafficCar> carQueue = _poolDictionary[randomEntry.prefab];
if (carQueue.Count == 0)
{
Debug.LogWarning($"Пул для {randomEntry.prefab.name} пуст!");
return null;
}
TrafficCar car = carQueue.Dequeue();
return car;
}
public void ReturnCar(TrafficCar car)
{
if (car.originalPrefab != null && _poolDictionary.ContainsKey(car.originalPrefab))
{
car.gameObject.SetActive(false);
_poolDictionary[car.originalPrefab].Enqueue(car);
}
else
{
Debug.LogWarning($"Не удалось вернуть машину {car.name} в пул. Уничтожение...");
Destroy(car.gameObject);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 2ea3f95c153019f4b8c84e1445b24d9f
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 8b4ec4000e1843c1a5de12cd1c8dde73
timeCreated: 1783938740
@@ -0,0 +1,155 @@
using System.Collections;
using UnityEngine;
using Boxes;
public class VanController : MonoBehaviour
{
[Header("Движение")]
public float forwardSpeed = 5.0f;
public float moveSpeed = 10.0f;
[Header("Спавн коробок")]
public BoxData[] availableBoxes;
public float spawnInterval = 0.5f;
public float boxEjectionForce = 2f;
public float boxTorqueForce = 5f;
[Header("AI Уклонения")]
public float detectionDistance = 40f;
public LayerMask trafficLayer;
private int _currentLaneIndex = 3;
private float _targetX;
private bool _isChangingLane;
private float _totalSpawnWeight;
private bool _isAlive = true;
private int[] _safeLanesBuffer;
private void OnEnable()
{
GameEvents.OnPlayerDied += StopActivities;
}
private void OnDisable()
{
GameEvents.OnPlayerDied -= StopActivities;
}
void Start()
{
_targetX = transform.position.x;
_totalSpawnWeight = 0;
foreach (var box in availableBoxes)
{
_totalSpawnWeight += box.spawnWeight;
}
_safeLanesBuffer = new int[RoadManager.Instance.GetLanesCount()];
StartCoroutine(SpawnBoxesInfinitely());
StartCoroutine(AvoidanceRoutine());
}
void Update()
{
if (!_isAlive) return;
transform.Translate(Vector3.forward * forwardSpeed * Time.deltaTime);
Vector3 newPos = transform.position;
newPos.x = Mathf.Lerp(newPos.x, _targetX, Time.deltaTime * moveSpeed);
transform.position = newPos;
}
private void StopActivities() => _isAlive = false;
IEnumerator SpawnBoxesInfinitely()
{
while (_isAlive)
{
yield return new WaitForSeconds(spawnInterval);
SpawnPhysicalBox();
}
}
void SpawnPhysicalBox()
{
BoxData boxToSpawn = GetRandomBoxType();
if (boxToSpawn == null || boxToSpawn.boxPrefab == null) return;
GameObject box = SimpleObjectPool.Instance.Get(boxToSpawn.boxPrefab, transform.position, Random.rotation);
Box boxComponent = box.GetComponent<Box>();
if (boxComponent != null) boxComponent.Init(boxToSpawn);
Rigidbody rb = box.GetComponent<Rigidbody>();
if (rb != null)
{
rb.linearVelocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
rb.AddForce(Vector3.back * boxEjectionForce, ForceMode.Impulse);
rb.AddTorque(Random.insideUnitSphere * boxTorqueForce, ForceMode.Impulse);
}
}
BoxData GetRandomBoxType()
{
if (availableBoxes.Length == 0) return null;
float randomValue = Random.Range(0, _totalSpawnWeight);
float currentWeight = 0;
foreach (var boxData in availableBoxes)
{
currentWeight += boxData.spawnWeight;
if (randomValue <= currentWeight) return boxData;
}
return null;
}
IEnumerator AvoidanceRoutine()
{
while (_isAlive)
{
yield return new WaitForSeconds(0.2f);
if (_isChangingLane) continue;
if (IsObstacleAhead()) TryToEvade();
}
}
bool IsObstacleAhead() => Physics.Raycast(transform.position, Vector3.forward, detectionDistance, trafficLayer);
void TryToEvade()
{
int safeLanesCount = 0;
int totalLanes = RoadManager.Instance.GetLanesCount();
for (int i = 0; i < totalLanes; i++)
{
if (i == _currentLaneIndex) continue;
float laneX = RoadManager.Instance.GetLaneX(i);
Vector3 checkPosition = new Vector3(laneX, transform.position.y, transform.position.z);
if (!Physics.Raycast(checkPosition, Vector3.forward, detectionDistance, trafficLayer))
{
_safeLanesBuffer[safeLanesCount] = i;
safeLanesCount++;
}
}
if (safeLanesCount > 0)
{
int chosenLane = _safeLanesBuffer[Random.Range(0, safeLanesCount)];
StartCoroutine(ChangeLane(chosenLane));
}
}
IEnumerator ChangeLane(int newLaneIndex)
{
_isChangingLane = true;
_currentLaneIndex = newLaneIndex;
_targetX = RoadManager.Instance.GetLaneX(newLaneIndex);
yield return new WaitForSeconds(0.6f);
_isChangingLane = false;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 81b21f534abfe3f4ea25b497737c5f83