сростил проекты
This commit is contained in:
1 parent
a4573f2d12
commit
dfd44aa129
684 files changed
+152796
-67
No files matched your search
@@ -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,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
|
||||
Reference in new issue
Block a user