first commit

This commit is contained in:
2026-06-04 17:00:04 +03:00
commit 18c4277523
70 changed files with 9539 additions and 0 deletions
+24
View File
@@ -0,0 +1,24 @@
using UnityEngine;
/// <summary>
/// Smooth top/back camera that keeps the player and generated path visible.
/// </summary>
public class CameraFollow : MonoBehaviour
{
public Transform target;
public Vector3 offset = new Vector3(0f, 8f, -8f);
public float followSpeed = 6f;
public float lookHeight = 1f;
private void LateUpdate()
{
if (target == null)
{
return;
}
Vector3 desiredPosition = target.position + offset;
transform.position = Vector3.Lerp(transform.position, desiredPosition, followSpeed * Time.deltaTime);
transform.LookAt(target.position + Vector3.up * lookHeight);
}
}
+11
View File
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 86be7a5eb87cf48deb7b7aca235b349c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+86
View File
@@ -0,0 +1,86 @@
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Runtime text HUD for generation parameters, counters and short status messages.
/// </summary>
public class LevelGenUI : MonoBehaviour
{
public Text titleText;
public Text hintsText;
public Text parametersText;
public Text statusText;
public Text messageText;
public float refreshInterval = 0.2f;
public LevelGenerator generator;
private float nextRefreshTime;
private float messageHideTime;
private void Start()
{
UpdateInfo();
}
private void Update()
{
if (Time.time >= nextRefreshTime)
{
UpdateInfo();
nextRefreshTime = Time.time + refreshInterval;
}
if (messageText != null && messageText.gameObject.activeSelf && Time.time > messageHideTime)
{
messageText.gameObject.SetActive(false);
}
}
public void SetGenerator(LevelGenerator generator)
{
this.generator = generator;
UpdateInfo();
}
public void UpdateInfo()
{
if (titleText != null)
{
titleText.text = "Лабораторная работа №1 — Процедурная генерация уровня";
}
if (hintsText != null)
{
hintsText.text = "WASD — движение\nSpace — прыжок\nR — пересоздать уровень";
}
if (parametersText != null && generator != null)
{
parametersText.text =
"Initial Platforms: " + generator.initialPlatformCount + "\n" +
"Step Distance: " + generator.stepDistance.ToString("0.0") + "\n" +
"Obstacle Chance: " + generator.obstacleChance.ToString("0.00") + "\n" +
"Alive Platforms: " + generator.GetAlivePlatformCount() + "\n" +
"Generated Total: " + generator.GetGeneratedCount();
}
if (statusText != null && generator != null)
{
statusText.text =
"Бесконечный режим: " + (generator.infiniteMode ? "включён" : "выключен") + "\n" +
"Старые платформы удаляются позади игрока";
}
}
public void ShowMessage(string message)
{
if (messageText == null)
{
return;
}
messageText.text = message;
messageText.gameObject.SetActive(true);
messageHideTime = Time.time + 2f;
}
}
+11
View File
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 455048cc87c1ca9fb87de97356c2cebd
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+380
View File
@@ -0,0 +1,380 @@
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Generates a simple endless platform path along the Z axis.
/// Platforms are spawned with small X offsets, old chunks are removed behind the player.
/// </summary>
public class LevelGenerator : MonoBehaviour
{
public GameObject[] platformPrefabs;
public Transform player;
public int initialPlatformCount = 12;
public float stepDistance = 3.5f;
public float generationThreshold = 12f;
public float removeThreshold = 18f;
public float obstacleChance = 0.3f;
public float sideOffsetRange = 2f;
public bool infiniteMode = true;
public int maxPlatformsAlive = 30;
public LevelGenUI ui;
public SimplePlayerController playerController;
[SerializeField]
private List<GameObject> spawnedPlatforms = new List<GameObject>();
private float lastGeneratedZ;
private int generatedCount;
private Vector3 initialPlayerPosition;
private Quaternion initialPlayerRotation;
private bool hasInitialPlayerPose;
private void Awake()
{
CacheInitialPlayerPose();
}
private void Start()
{
if (ui != null)
{
ui.SetGenerator(this);
}
RegenerateLevel(false);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.R))
{
RegenerateLevel();
}
if (player == null)
{
return;
}
RemoveOldPlatforms();
if (!infiniteMode)
{
return;
}
// Limit catch-up generation so a temporary teleport cannot spawn an uncontrolled amount in one frame.
int generatedThisFrame = 0;
while (player.position.z + generationThreshold > lastGeneratedZ &&
spawnedPlatforms.Count < maxPlatformsAlive &&
generatedThisFrame < 4)
{
GenerateNextPlatform();
generatedThisFrame++;
}
}
public void GenerateInitialLevel()
{
ClearGeneratedLevel();
if (player == null || platformPrefabs == null || platformPrefabs.Length == 0)
{
Debug.LogWarning("LevelGenerator requires a player and at least one platform prefab.");
return;
}
generatedCount = 0;
Vector3 startPosition = player.position;
lastGeneratedZ = startPosition.z - stepDistance;
for (int i = 0; i < initialPlatformCount; i++)
{
GenerateNextPlatform();
}
if (spawnedPlatforms.Count > 0)
{
PlacePlayerOnPlatform(spawnedPlatforms[0]);
}
}
public GameObject GenerateNextPlatform()
{
if (platformPrefabs == null || platformPrefabs.Length == 0)
{
return null;
}
bool firstPlatform = generatedCount == 0;
GameObject prefab = ChoosePlatformPrefab(firstPlatform);
if (prefab == null)
{
return null;
}
float x = firstPlatform || player == null
? (player != null ? player.position.x : 0f)
: Random.Range(-sideOffsetRange, sideOffsetRange);
lastGeneratedZ += Mathf.Max(2.5f, stepDistance);
Vector3 position = new Vector3(x, 0f, firstPlatform && player != null ? player.position.z : lastGeneratedZ);
GameObject platform = Instantiate(prefab, position, Quaternion.identity, transform);
platform.name = prefab.name + "_" + generatedCount.ToString("000");
PlatformInfo info = platform.GetComponent<PlatformInfo>();
if (info != null)
{
info.generatedIndex = generatedCount;
info.isSafe = firstPlatform || info.platformType != PlatformInfo.PlatformType.Obstacle;
}
spawnedPlatforms.Add(platform);
generatedCount++;
return platform;
}
public void RemoveOldPlatforms()
{
if (player == null)
{
return;
}
for (int i = spawnedPlatforms.Count - 1; i >= 0; i--)
{
GameObject platform = spawnedPlatforms[i];
if (platform == null)
{
spawnedPlatforms.RemoveAt(i);
continue;
}
if (platform.transform.position.z < player.position.z - removeThreshold)
{
spawnedPlatforms.RemoveAt(i);
DestroyPlatform(platform);
}
}
}
public void ClearGeneratedLevel()
{
HashSet<GameObject> scheduledForDestroy = new HashSet<GameObject>();
for (int i = spawnedPlatforms.Count - 1; i >= 0; i--)
{
if (spawnedPlatforms[i] != null)
{
scheduledForDestroy.Add(spawnedPlatforms[i]);
DestroyPlatform(spawnedPlatforms[i]);
}
}
spawnedPlatforms.Clear();
// Also remove generated children if the serialized list was lost after domain reload.
for (int i = transform.childCount - 1; i >= 0; i--)
{
Transform child = transform.GetChild(i);
if (child != null && !scheduledForDestroy.Contains(child.gameObject))
{
DestroyPlatform(child.gameObject);
}
}
}
public void RegenerateLevel()
{
RegenerateLevel(true);
}
public void RegenerateLevel(bool showMessage)
{
CacheInitialPlayerPose();
ResetPlayer();
GenerateInitialLevel();
if (ui != null)
{
ui.UpdateInfo();
if (showMessage)
{
ui.ShowMessage("Уровень пересоздан");
}
}
}
public int GetGeneratedCount()
{
return generatedCount;
}
public int GetAlivePlatformCount()
{
return spawnedPlatforms.Count;
}
private GameObject ChoosePlatformPrefab(bool firstPlatform)
{
if (firstPlatform)
{
return platformPrefabs[0];
}
int obstacleIndex = FindObstaclePrefabIndex();
if (obstacleIndex >= 0 && Random.value < obstacleChance)
{
return platformPrefabs[obstacleIndex];
}
List<GameObject> regularPrefabs = new List<GameObject>();
for (int i = 0; i < platformPrefabs.Length; i++)
{
if (i != obstacleIndex && platformPrefabs[i] != null)
{
regularPrefabs.Add(platformPrefabs[i]);
}
}
if (regularPrefabs.Count == 0)
{
return platformPrefabs[0];
}
return regularPrefabs[Random.Range(0, regularPrefabs.Count)];
}
private int FindObstaclePrefabIndex()
{
for (int i = 0; i < platformPrefabs.Length; i++)
{
GameObject prefab = platformPrefabs[i];
if (prefab == null)
{
continue;
}
PlatformInfo info = prefab.GetComponent<PlatformInfo>();
if (info != null && info.platformType == PlatformInfo.PlatformType.Obstacle)
{
return i;
}
}
return -1;
}
private void CacheInitialPlayerPose()
{
if (hasInitialPlayerPose || player == null)
{
return;
}
initialPlayerPosition = player.position;
initialPlayerRotation = player.rotation;
hasInitialPlayerPose = true;
}
private void ResetPlayer()
{
if (player == null || !hasInitialPlayerPose)
{
return;
}
player.position = initialPlayerPosition;
player.rotation = initialPlayerRotation;
if (playerController == null)
{
playerController = player.GetComponent<SimplePlayerController>();
}
if (playerController != null)
{
playerController.ResetToPosition(initialPlayerPosition);
}
}
private void PlacePlayerOnPlatform(GameObject platform)
{
if (player == null || platform == null)
{
return;
}
if (!TryGetColliderBounds(platform, out Bounds bounds))
{
return;
}
CapsuleCollider capsule = player.GetComponent<CapsuleCollider>();
float bottomOffset = 1f;
if (capsule != null)
{
bottomOffset = (capsule.height * 0.5f * player.lossyScale.y) - (capsule.center.y * player.lossyScale.y);
}
Vector3 safePosition = new Vector3(
bounds.center.x,
bounds.max.y + bottomOffset + 0.05f,
bounds.center.z);
if (playerController == null)
{
playerController = player.GetComponent<SimplePlayerController>();
}
if (playerController != null)
{
playerController.ResetToPosition(safePosition);
}
else
{
player.position = safePosition;
}
}
private bool TryGetColliderBounds(GameObject platform, out Bounds bounds)
{
Collider[] colliders = platform.GetComponentsInChildren<Collider>();
bounds = new Bounds(platform.transform.position, Vector3.zero);
bool hasBounds = false;
for (int i = 0; i < colliders.Length; i++)
{
Collider collider = colliders[i];
if (collider == null || collider.isTrigger)
{
continue;
}
if (!hasBounds)
{
bounds = collider.bounds;
hasBounds = true;
}
else
{
bounds.Encapsulate(collider.bounds);
}
}
return hasBounds;
}
private void DestroyPlatform(GameObject platform)
{
if (Application.isPlaying)
{
Destroy(platform);
}
else
{
DestroyImmediate(platform);
}
}
}
+11
View File
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9dbf56311a510b5bea85d342eb39300f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+20
View File
@@ -0,0 +1,20 @@
using UnityEngine;
/// <summary>
/// Stores lightweight metadata about a generated platform.
/// The generator and UI can use this for debugging and display.
/// </summary>
public class PlatformInfo : MonoBehaviour
{
public enum PlatformType
{
Basic,
Wide,
Narrow,
Obstacle
}
public PlatformType platformType = PlatformType.Basic;
public int generatedIndex;
public bool isSafe = true;
}
+11
View File
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9ec3ea738b9a87ea3b71d9f612198a5d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+146
View File
@@ -0,0 +1,146 @@
using UnityEngine;
/// <summary>
/// Minimal Rigidbody-based third-person controller for the lab prototype.
/// Uses the classic Unity input axes, so it works in a default 3D template.
/// </summary>
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CapsuleCollider))]
public class SimplePlayerController : MonoBehaviour
{
public float moveSpeed = 6f;
public float jumpForce = 7f;
public float groundCheckRadius = 0.25f;
public LayerMask groundMask = ~0;
public float fallResetY = -10f;
public Transform respawnPoint;
public Vector3 lastSafePosition;
private Rigidbody rb;
private CapsuleCollider capsuleCollider;
private Collider[] ownColliders;
private bool isGrounded;
private void Awake()
{
rb = GetComponent<Rigidbody>();
capsuleCollider = GetComponent<CapsuleCollider>();
ownColliders = GetComponentsInChildren<Collider>();
rb.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ;
lastSafePosition = transform.position;
}
private void Update()
{
UpdateGroundedState();
if (Input.GetKeyDown(KeyCode.Space) && isGrounded && rb.velocity.y <= 0.1f)
{
Vector3 velocity = rb.velocity;
velocity.y = 0f;
rb.velocity = velocity;
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
if (transform.position.y < fallResetY)
{
ResetToLastSafePosition();
}
}
private void FixedUpdate()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 input = new Vector3(horizontal, 0f, vertical);
if (input.sqrMagnitude > 1f)
{
input.Normalize();
}
Vector3 horizontalVelocity = input * moveSpeed;
rb.velocity = new Vector3(horizontalVelocity.x, rb.velocity.y, horizontalVelocity.z);
if (input.sqrMagnitude > 0.01f)
{
Quaternion targetRotation = Quaternion.LookRotation(input, Vector3.up);
rb.MoveRotation(Quaternion.Slerp(rb.rotation, targetRotation, 12f * Time.fixedDeltaTime));
}
if (isGrounded && rb.velocity.y <= 0.05f)
{
lastSafePosition = transform.position;
}
}
public void ResetToPosition(Vector3 position)
{
if (rb == null)
{
rb = GetComponent<Rigidbody>();
}
transform.position = position;
lastSafePosition = position;
if (rb != null)
{
rb.velocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
}
}
public void ResetToLastSafePosition()
{
Vector3 target = respawnPoint != null ? respawnPoint.position : lastSafePosition;
ResetToPosition(target + Vector3.up * 0.25f);
}
private void UpdateGroundedState()
{
Vector3 capsuleCenter = transform.TransformPoint(capsuleCollider.center);
Vector3 sphereCenter = capsuleCenter + Vector3.down * ((capsuleCollider.height * 0.5f) - (groundCheckRadius * 0.5f));
Collider[] hits = Physics.OverlapSphere(
sphereCenter,
groundCheckRadius,
groundMask,
QueryTriggerInteraction.Ignore);
isGrounded = false;
for (int i = 0; i < hits.Length; i++)
{
Collider hit = hits[i];
if (hit == null || IsOwnCollider(hit))
{
continue;
}
// A valid jump surface must be below the player's feet, not inside the player body.
if (hit.bounds.max.y <= sphereCenter.y + groundCheckRadius)
{
isGrounded = true;
return;
}
}
}
private bool IsOwnCollider(Collider collider)
{
if (ownColliders == null || ownColliders.Length == 0)
{
ownColliders = GetComponentsInChildren<Collider>();
}
for (int i = 0; i < ownColliders.Length; i++)
{
if (ownColliders[i] == collider)
{
return true;
}
}
return false;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 906b7a39ca8f9f8ff884e5f7cdffeeee
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: