Perekyp/Assets/Scripts/Car/CarOrbitCamera.cs

65 lines
3.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using UnityEngine;
public class CarOrbitCamera : MonoBehaviour
{
[Header("Цель")]
[SerializeField] private Transform target; // Корневой объект машины
[SerializeField] private Vector3 targetOffset = new Vector3(0, 1.2f, 0); // Смещение центра (чтобы смотреть на крышу, а не под колеса)
[Header("Настройки орбиты")]
[SerializeField] private float distance = 5.5f; // Дистанция от машины
[SerializeField] private float mouseSensitivity = 150f; // Чувствительность мыши
[Header("Ограничения (чтобы камера не уходила под землю)")]
[SerializeField] private float yMinLimit = 0f; // Минимальный угол (0 = уровень земли)
[SerializeField] private float yMaxLimit = 80f; // Максимальный угол (вид сверху)
private float currentX = 0f; // Поворот по горизонтали
private float currentY = 20f; // Поворот по вертикали (начинаем с легкого наклона)
private void Start()
{
// При старте (или посадке) задаем начальный угол, чтобы камера смотрела в ту же сторону, куда и капот
if (target != null)
{
currentX = target.eulerAngles.y;
}
}
// Вызывается после того, как все объекты (включая машину) уже сдвинулись
private void LateUpdate()
{
if (target == null) return;
// 1. Читаем движение мыши
currentX += Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
currentY -= Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
// 2. Ограничиваем угол по вертикали, чтобы камера не перекрутилась через крышу или не ушла в асфальт
currentY = Mathf.Clamp(currentY, yMinLimit, yMaxLimit);
// 3. Вычисляем новое вращение камеры на основе углов
Quaternion rotation = Quaternion.Euler(currentY, currentX, 0);
// 4. Вычисляем точку, вокруг которой крутимся (центр машины + смещение вверх)
Vector3 focusPoint = target.position + targetOffset;
// 5. Вычисляем финальную позицию камеры: отходим назад от фокусной точки на расстояние distance
Vector3 position = focusPoint - (rotation * Vector3.forward * distance);
// 6. Применяем позицию и вращение
transform.position = position;
transform.rotation = rotation;
}
// Метод для вызова из скрипта VehicleInteraction (опционально)
// Чтобы камера всегда сбрасывалась ровно за машину, когда игрок садится в неё
public void ResetCameraAngles()
{
if (target != null)
{
currentX = target.eulerAngles.y;
currentY = 20f;
}
}
}