теперь камера норм пашет и стены
This commit is contained in:
1 parent
f21e56a9f1
commit
4adfb81d1d
78 files changed
+8495
-87
No files matched your search
@@ -1,78 +1,138 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
public class CameraController : MonoBehaviour
|
||||
{
|
||||
|
||||
[Header("Настройки позиции камеры")]
|
||||
[Tooltip("Расстояние от камеры до центра (радиус вращения)")]
|
||||
[Range(2, 8)]
|
||||
[Header("Настройки позиции камеры (Зум)")]
|
||||
[Tooltip("Стартовое расстояние от камеры до цели")]
|
||||
public float distance = 10f;
|
||||
|
||||
[Tooltip("Высота камеры над полом")]
|
||||
public float addingHeight = 5f;
|
||||
public float minDistance = 3f;
|
||||
public float maxDistance = 30f;
|
||||
public float zoomSpeed = 0.05f;
|
||||
|
||||
[Header("Настройки цели (Ось Y)")]
|
||||
[Tooltip("Стартовая высота цели на оси Y")]
|
||||
public float targetY = 0f;
|
||||
public float minTargetY = 0f;
|
||||
public float maxTargetY = 15f;
|
||||
public float moveTargetSpeed = 0.02f;
|
||||
public float addingHeight = 3f;
|
||||
|
||||
[Header("Настройки вращения")]
|
||||
[Tooltip("Общая скорость вращения (влияет на стрелочки и свайпы)")]
|
||||
public float rotationSpeed = 50f;
|
||||
|
||||
[Tooltip("Чувствительность для сенсора/тачпада")]
|
||||
public float touchSensitivity = 0.2f;
|
||||
|
||||
// Текущий угол поворота камеры в градусах
|
||||
public float rotationSpeed = 0.2f;
|
||||
[SerializeField]
|
||||
private float currentAngle = -45f;
|
||||
|
||||
[Header("Настройки плавности (Сглаживание)")]
|
||||
[Tooltip("Время сглаживания. Чем больше значение, тем более плавно и с большей инерцией движется камера.")]
|
||||
[Range(0.01f, 0.5f)]
|
||||
public float smoothTime = 0.1f;
|
||||
|
||||
// Точка, вокруг которой крутимся (центр пола)
|
||||
private Vector3 centerPoint = Vector3.zero;
|
||||
[Tooltip("Мертвая зона в пикселях. Отсекает микро-дрожание пальцев.")]
|
||||
public float touchDeadZone = 1.5f;
|
||||
|
||||
// ЦЕЛЕВЫЕ значения (куда камера должна стремиться прийти)
|
||||
private float _targetAngle;
|
||||
private float _targetY;
|
||||
private float _targetDistance;
|
||||
|
||||
// Внутренние переменные скорости (необходимы для работы функции Mathf.SmoothDamp)
|
||||
private float _angleVelocity;
|
||||
private float _yVelocity;
|
||||
private float _distanceVelocity;
|
||||
|
||||
void Start()
|
||||
{
|
||||
// Устанавливаем камеру в правильную позицию при старте игры
|
||||
// Инициализируем целевые значения текущими при старте, чтобы камера не прыгала
|
||||
_targetAngle = currentAngle;
|
||||
_targetY = targetY;
|
||||
_targetDistance = distance;
|
||||
|
||||
UpdateCameraPosition();
|
||||
}
|
||||
|
||||
void LateUpdate()
|
||||
{
|
||||
// 1. Управление через тач/сенсорный экран
|
||||
if (Input.touchCount > 0)
|
||||
HandleInput();
|
||||
SmoothMovement();
|
||||
UpdateCameraPosition();
|
||||
}
|
||||
|
||||
private void HandleInput()
|
||||
{
|
||||
// === 1. УПРАВЛЕНИЕ ОДНИМ ПАЛЬЦЕМ (Вращение и высота) ===
|
||||
if (Input.touchCount == 1)
|
||||
{
|
||||
Touch touch = Input.GetTouch(0);
|
||||
if (touch.phase == TouchPhase.Moved)
|
||||
|
||||
// Проверяем, сдвинулся ли палец дальше "мертвой зоны", чтобы игнорировать дрожание
|
||||
if (touch.phase == TouchPhase.Moved && touch.deltaPosition.sqrMagnitude > touchDeadZone * touchDeadZone)
|
||||
{
|
||||
// Смещаем угол в зависимости от движения пальца по оси X
|
||||
currentAngle += touch.deltaPosition.x * touchSensitivity * rotationSpeed * Time.deltaTime;
|
||||
// Меняем ЦЕЛЕВЫЕ значения, а не саму камеру
|
||||
_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);
|
||||
}
|
||||
}
|
||||
// === 3. МЫШЬ (Для редактора ПК) ===
|
||||
else if (Input.GetMouseButton(0))
|
||||
{
|
||||
currentAngle += Input.GetAxis("Mouse X") * touchSensitivity * rotationSpeed * 50f * Time.deltaTime;
|
||||
}
|
||||
// 2. Костыль: управление стрелочками Влево/Вправо (или A/D)
|
||||
else if (Input.GetAxis("Horizontal") != 0)
|
||||
{
|
||||
float horizontalInput = Input.GetAxis("Horizontal");
|
||||
currentAngle += horizontalInput * rotationSpeed * Time.deltaTime;
|
||||
_targetAngle += Input.GetAxis("Mouse X") * rotationSpeed * 20f;
|
||||
_targetY -= Input.GetAxis("Mouse Y") * moveTargetSpeed * 20f;
|
||||
_targetY = Mathf.Clamp(_targetY, minTargetY, maxTargetY);
|
||||
}
|
||||
|
||||
// Применяем вычисленный угол для перемещения камеры
|
||||
UpdateCameraPosition();
|
||||
// Зум колесиком мыши
|
||||
float scroll = Input.GetAxis("Mouse ScrollWheel");
|
||||
if (scroll != 0)
|
||||
{
|
||||
_targetDistance -= scroll * zoomSpeed * 100f;
|
||||
_targetDistance = Mathf.Clamp(_targetDistance, minDistance, maxDistance);
|
||||
}
|
||||
}
|
||||
|
||||
private void SmoothMovement()
|
||||
{
|
||||
// Функция SmoothDamp плавно "подтягивает" текущее значение к целевому.
|
||||
// Это создает эффект пружины и инерции.
|
||||
currentAngle = Mathf.SmoothDamp(currentAngle, _targetAngle, ref _angleVelocity, smoothTime);
|
||||
targetY = Mathf.SmoothDamp(targetY, _targetY, ref _yVelocity, smoothTime);
|
||||
distance = Mathf.SmoothDamp(distance, _targetDistance, ref _distanceVelocity, smoothTime);
|
||||
}
|
||||
|
||||
private void UpdateCameraPosition()
|
||||
{
|
||||
// Переводим градусы в радианы для использования в математических функциях
|
||||
// Цель на оси Y с ПЛАВНОЙ высотой (targetY)
|
||||
Vector3 targetPoint = new Vector3(0, targetY, 0);
|
||||
|
||||
float radians = currentAngle * Mathf.Deg2Rad;
|
||||
|
||||
// Вычисляем координаты X и Z на окружности (используя синус и косинус)
|
||||
float x = centerPoint.x + distance * Mathf.Sin(radians);
|
||||
float z = centerPoint.z + distance * Mathf.Cos(radians);
|
||||
// Вычисляем ПЛАВНЫЕ координаты X и Z
|
||||
float x = targetPoint.x + distance * Mathf.Sin(radians);
|
||||
float z = targetPoint.z + distance * Mathf.Cos(radians);
|
||||
|
||||
// Устанавливаем новую позицию камеры (X и Z на окружности, Y - заданная высота)
|
||||
transform.position = new Vector3(x, addingHeight, z);
|
||||
|
||||
// Заставляем камеру смотреть ровно в центр сцены (0, 0, 0)
|
||||
transform.LookAt(centerPoint);
|
||||
transform.position = new Vector3(x, targetY + addingHeight, z);
|
||||
transform.LookAt(targetPoint);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user