138 lines
5.6 KiB
C#
138 lines
5.6 KiB
C#
using UnityEngine;
|
|
|
|
public class CameraController : MonoBehaviour
|
|
{
|
|
[Header("Настройки позиции камеры (Зум)")]
|
|
[Tooltip("Стартовое расстояние от камеры до цели")]
|
|
public float distance = 10f;
|
|
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("Настройки вращения")]
|
|
public float rotationSpeed = 0.2f;
|
|
[SerializeField]
|
|
private float currentAngle = -45f;
|
|
|
|
[Header("Настройки плавности (Сглаживание)")]
|
|
[Tooltip("Время сглаживания. Чем больше значение, тем более плавно и с большей инерцией движется камера.")]
|
|
[Range(0.01f, 0.5f)]
|
|
public float smoothTime = 0.1f;
|
|
|
|
[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()
|
|
{
|
|
HandleInput();
|
|
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);
|
|
}
|
|
}
|
|
// === 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);
|
|
}
|
|
|
|
// Зум колесиком мыши
|
|
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 = 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);
|
|
}
|
|
} |