using System.Collections.Generic; using UnityEngine; public class PlayerScript : MonoBehaviour { public Transform target; public Vector3 offset; public float sensitivity = 3; // чувствительность мышки public float limit = 80; // ограничение вращения по Y public float zoom = 0.25f; // чувствительность при увеличении, колесиком мышки public float zoomMax = 10; // макс. увеличение public float zoomMin = 3; // мин. увеличение public float X, Y; RayClusterFinder rayClusterFinder; void Start() { rayClusterFinder = new RayClusterFinder(); } Vector3 playerOffset = new Vector3(0,1.5f,0); Vector3 lastPlayerPosition = new Vector3(), lastCameraPosition = new Vector3(); public static Quaternion GetRotationBetweenVectors(Vector3 a, Vector3 b) { // Нормализуем векторы (на случай, если они не нормализованы) a = a.normalized; b = b.normalized; // Если векторы коллинеарны: if (a == b) return Quaternion.identity; // Нет вращения if (a == -b) { // Если векторы противоположны, выбираем произвольную ось, перпендикулярную `a` Vector3 axis1 = (Mathf.Abs(a.x) > 0.9f) ? Vector3.Cross(a, Vector3.up).normalized : Vector3.Cross(a, Vector3.right).normalized; return Quaternion.AngleAxis(180f, axis1); } // Ось вращения (нормализованное векторное произведение) Vector3 axis = Vector3.Cross(a, b).normalized; // Угол вращения (через скалярное произведение) float angle = Mathf.Acos(Vector3.Dot(a, b)) * Mathf.Rad2Deg; // Возвращаем кватернион return Quaternion.AngleAxis(angle, axis); } public static Quaternion GetRotationBetweenVectorsWithZeroZ(Vector3 a, Vector3 b) { // Нормализуем векторы a = a.normalized; b = b.normalized; // Если векторы коллинеарны if (a == b) return Quaternion.identity; if (a == -b) { // Для противоположных векторов выбираем ось, перпендикулярную a и лежащую в плоскости XY Vector3 axis1 = new Vector3(-a.y, a.x, 0).normalized; return Quaternion.AngleAxis(180f, axis1); } // Находим ось вращения Vector3 axis = Vector3.Cross(a, b).normalized; // Проецируем ось на плоскость XY, чтобы исключить Z-компоненту Vector3 flatAxis = new Vector3(axis.x, axis.y, 0).normalized; // Если проекция нулевая (векторы отличаются только по Z), // используем ось X или Y if (flatAxis == Vector3.zero) { flatAxis = Vector3.up; } // Вычисляем угол между векторами float angle = Mathf.Acos(Vector3.Dot(a, b)) * Mathf.Rad2Deg; // Создаем кватернион с нулевым поворотом вокруг Z Quaternion rotation = Quaternion.AngleAxis(angle, flatAxis); // Дополнительно убедимся, что в кватернионе нет поворота вокруг Z Vector3 euler = rotation.eulerAngles; return Quaternion.Euler(euler.x, euler.y, 0); } static float GetDeltaAzimut(float a, float b) { // Нормализуем углы в диапазон [0, 360) a = (a % 360 + 360) % 360; b = (b % 360 + 360) % 360; // Вычисляем разницу float delta = b - a; // Корректируем разницу до минимального значения if (delta > 180) delta -= 360; else if (delta < -180) delta += 360; return delta; //if (a < 0) //{ // a = a * -1 + 180; //} //if (b < 0) //{ // b = b * -1 + 180; //} //return b - a; } public static Quaternion GetRotationBetweenVectorsWithZeroZ1(Vector3 a, Vector3 b, out float deltaZenith, out float deltaAzimuth) { // Нормализация векторов a = a.normalized; b = b.normalized; // Азимут и зенит для A float azimuthA = Mathf.Atan2(a.z, a.x) * Mathf.Rad2Deg; float zenithA = Mathf.Acos(a.y) * Mathf.Rad2Deg; // Азимут и зенит для B float azimuthB = Mathf.Atan2(b.z, b.x) * Mathf.Rad2Deg; float zenithB = Mathf.Acos(b.y) * Mathf.Rad2Deg; // Разница азимутов (с учётом цикличности) //float deltaAzimuth = Mathf.DeltaAngle(azimuthA, azimuthB); // Разница зенитов deltaZenith = zenithB - zenithA; //Quaternion.Euler(0, 90f, 0f) * Vector3(0, 0, 1) == Vector3(1,0,0); deltaAzimuth = GetDeltaAzimut(azimuthA,azimuthB); Quaternion finalRot = Quaternion.Euler(deltaZenith, -deltaAzimuth, 0f); // Проверка (опционально) Vector3 rotatedA = finalRot * a; if ((rotatedA - b).magnitude > 0.01f) { deltaZenith *= -1; finalRot = Quaternion.Euler(deltaZenith, -deltaAzimuth, 0f); rotatedA = finalRot * a; if ((rotatedA - b).magnitude > 0.01f) { Debug.LogWarning("Погрешность превышает допустимую!"); } } return finalRot; } void FixedUpdate() { if (SceneParams.Instance.cameraSettings.IsAutoRotateCamera == false || SceneParams.Instance.cameraSettings.IsStartPos) return; if (lastPlayerPosition == target.transform.position && lastCameraPosition == transform.position) return; lastPlayerPosition = target.transform.position; lastCameraPosition = transform.position; Vector3 player = target.transform.position; player += playerOffset; Vector3[] checkiablePoints = new Vector3[3] { new Vector3(player.x,player.y,player.z+0.1f), new Vector3(player.x,player.y,player.z+1.0f), new Vector3(player.x, player.y, player.z+1.8f) }; bool isCast = false; Vector3 direction; foreach (var point in checkiablePoints) { direction = transform.position - point; if (Physics.Raycast(point, direction.normalized, out var hit, Vector3.Distance(point, transform.position))){ isCast = true; break; } } if (isCast) { Debug.Log($"{player} - {transform.position}"); Vector3 newPosition = rayClusterFinder.Calculate(checkiablePoints); // 1. Вычисляем новое смещение float distance = Vector3.Distance(target.position, newPosition); // 2. Устанавливаем смещение по оси Z // Расчёт Z вектора для констатных двух параметров x,y (0,1,z) offset.z = Mathf.Sqrt(distance * distance - 1); offset.z *= -1; //transform.LookAt(target); //return; // 3. Вычисляем направление от новой позиции камеры к объекту Vector3 directionToTarget = (newPosition-target.position); // 4. Вычисляем вращение на основе направления //Quaternion rotation = GetRotationBetweenVectors(offset, directionToTarget); Quaternion rotation = GetRotationBetweenVectorsWithZeroZ1(offset, directionToTarget, out var deltaZenith, out var deltaAzimuth); //Quaternion.Euler(deltaZenith, -deltaAzimuth, 0f); //Quaternion.Euler(-Y, X, 0f); // Y = deltaZenit // X = -deltaAzimut // //offset *= -1; //deltaZenith = 180.0f - deltaZenith; //deltaAzimuth = deltaAzimuth + 180.0f; //rotation = Quaternion.Inverse(rotation); //rotation = Quaternion.Euler(deltaZenith, -(deltaAzimuth), 0f); Y = -deltaZenith; X = -deltaAzimuth; // 5. Применяем вращение к локальной ротации объекта transform.localRotation = rotation; // 6. Обновляем позицию камеры с учетом смещения // Здесь мы используем локальную ротацию для расчета новой позиции Vector3 calculatedPosition = transform.localRotation * offset + target.position; // 7. Устанавливаем позицию камеры //transform.position = calculatedPosition; lastCameraPosition = calculatedPosition; // 8. Проверяем, совпадает ли рассчитанная позиция с заданной distance = Vector3.Distance(newPosition, calculatedPosition); if (distance < 0.01f) { Debug.Log("Рассчитано верно"); } else { Debug.Log("Рассчитано не верно"); } } } public void SetPlayerPosition() { limit = Mathf.Abs(limit); if (limit > 90) limit = 90; offset = new Vector3(offset.x, offset.y, -Mathf.Abs(zoomMax) / 2); transform.position = target.position + offset; } void Update() { if (SceneParams.Instance.cameraSettings.IsBlockZoom == false) { if (Input.GetAxis("Mouse ScrollWheel") > 0) offset.z += zoom; else if (Input.GetAxis("Mouse ScrollWheel") < 0) offset.z -= zoom; offset.z = Mathf.Clamp(offset.z, -Mathf.Abs(zoomMax), -Mathf.Abs(zoomMin)); } if (SceneParams.Instance.cameraSettings.IsBlockMove == false) { if (Input.GetMouseButton(0)) { X = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivity; Y += Input.GetAxis("Mouse Y") * sensitivity; Y = Mathf.Clamp(Y, -limit, limit); transform.localEulerAngles = new Vector3(-Y, X, 0); } } // Обновляем позицию в каждом кадре if (SceneParams.Instance.cameraSettings.IsStartPos == false) { transform.position = transform.localRotation * offset + target.position; } } } public class RayClusterFinder { public float proximityRadius = 5f; // Радиус для поиска ближайших лучей public float maxDistance = 10f; // Максимальная длина луча public float minDistance = 3f; // Максимальная длина луча public float upperZenithAngle = 5f; // Угол верхнего зенита public float lowerZenithAngle = -35f; // Угол нижнего зенита public float azimuthStep = 10f; // Шаг по азимуту private List rayOrigins = new List(); // Список для хранения начальных точек лучей public RayClusterFinder() { } Vector3 bestVertex; public Vector3 Calculate(Vector3[] origin) { //CastRays(); CastSphericalRays(origin); FindRayWithMostNeighbors(origin); return bestVertex; } void CastSphericalRays(Vector3[] originArr) { rayOrigins.Clear(); foreach (var origin in originArr) { // Преобразуем углы в радианы float upperZenithRad = (upperZenithAngle + 90) * Mathf.Deg2Rad; float lowerZenithRad = (lowerZenithAngle + 90) * Mathf.Deg2Rad; float azimuthStepRad = azimuthStep * Mathf.Deg2Rad; // Генерация лучей for (float zenith = lowerZenithRad; zenith <= upperZenithRad; zenith += azimuthStepRad) { for (float azimuth = 0; azimuth < 360 * Mathf.Deg2Rad; azimuth += azimuthStepRad) { // Вычисляем направление луча float x = Mathf.Sin(zenith) * Mathf.Cos(azimuth); float y = Mathf.Cos(zenith); float z = Mathf.Sin(zenith) * Mathf.Sin(azimuth); Vector3 direction = new Vector3(x, y, z).normalized; // Позиция начала луча (центр капсулы) // Отправляем луч RaycastHit hit; if (Physics.Raycast(origin, direction, out hit, maxDistance)) { // Проверяем, если расстояние до столкновения меньше или равно maxDistance if (hit.distance <= maxDistance && hit.distance >= minDistance) { rayOrigins.Add(hit.point); // Сохраняем валидное столкновение //Debug.DrawLine(origin, hit.point, Color.red, 1000000); // Отображаем луч до столкновения //Debug.Log($"Hit: {hit.collider.name} at {hit.point}"); } } else { rayOrigins.Add(origin + direction * maxDistance); //Debug.DrawRay(origin, direction * maxDistance, Color.green, 1000000); // Отображаем луч, если нет столкновения } } } } } void FindRayWithMostNeighbors(Vector3[] originalCenterArr) { Vector3 originalCenter = Vector3.zero; // 1. Calculate the center of all points foreach (var origin in originalCenterArr) { originalCenter += origin; } originalCenter /= rayOrigins.Count; // Divide by the number of points to get the center int maxNeighbors = 0; List neighborsVertex = new List(); Vector3 center = Vector3.zero; // 1. Calculate the center of all points foreach (var origin in rayOrigins) { center += origin; } center /= rayOrigins.Count; // Divide by the number of points to get the center // 2. Find rays with the most neighbors foreach (var origin in rayOrigins) { int neighborCount = 0; foreach (var otherOrigin in rayOrigins) { if (origin != otherOrigin && Vector3.Distance(origin, otherOrigin) <= proximityRadius) { neighborCount++; } } if (neighborCount > maxNeighbors) { neighborsVertex.Clear(); maxNeighbors = neighborCount; neighborsVertex.Add(origin); } else if (neighborCount == maxNeighbors) { neighborsVertex.Add(origin); } } // 3. Find the vector from the original center to the calculated center Vector3 directionToCenter = (center - originalCenter).normalized; // 4. Find the point that has the closest direction to this vector Vector3 closestVertex = Vector3.zero; float closestAngle = float.MaxValue; foreach (var vertex in neighborsVertex) { Debug.DrawLine(originalCenter, vertex, Color.green, 15); Vector3 directionFromOriginal = (vertex - originalCenter).normalized; // Direction from original center to the vertex float angle = Vector3.Angle(directionToCenter, directionFromOriginal); // Calculate the angle between the two directions if (angle < closestAngle) { closestAngle = angle; closestVertex = vertex; } } //Debug.Log($"Closest direction to the center: {closestVertex}"); //Debug.Log($"Center0: {originalCenter}"); //Debug.Log($"Center1: {center}"); //Debug.Log($"vector: {center - originalCenter}"); bestVertex = closestVertex; Debug.DrawLine(originalCenter, originalCenter + (center-originalCenter).normalized * 10f, Color.red, 15); Debug.DrawLine(originalCenter, originalCenter + (closestVertex- originalCenter) * 1.5f, Color.blue, 15); } }