Files
3DBlobici-WorkingTitle/3D blobici/Assets/Scripts/Player/CameraManager.cs

79 lines
2.3 KiB
C#
Raw Normal View History

2025-06-23 16:30:18 +02:00
using UnityEngine;
public class CameraManager : MonoBehaviour
{
[Header("Target Settings")]
public Transform target;
[Header("Position Settings")]
public Vector3 offset = new Vector3(0f, 10f, -5f);
public float followSpeed = 10f;
[Header("Zoom Settings")]
public float zoomSpeed = 5f;
public float minZoomHeight = 5f;
public float maxZoomHeight = 15f;
public float zoomZRatio = 0.5f; // How much Z changes relative to Y when zooming
// Current zoom level (0 = min zoom, 1 = max zoom)
private float zoomLevel = 0.5f;
// Fixed camera rotation
public Vector3 cameraRotation = new Vector3(45f, 0f, 0f);
void Start()
{
if (target == null)
{
Debug.LogWarning("No target assigned to CameraManager!");
return;
}
// Set initial rotation
transform.eulerAngles = cameraRotation;
// Position the camera immediately at start
UpdateCameraPosition(false);
}
void LateUpdate()
{
if (target == null)
return;
// Handle zoom input
float scrollInput = Input.GetAxis("Mouse ScrollWheel");
if (scrollInput != 0)
{
// Update zoom level
zoomLevel = Mathf.Clamp01(zoomLevel - scrollInput * zoomSpeed * Time.deltaTime);
}
// Update camera position with smoothing
UpdateCameraPosition(true);
// Ensure the camera rotation stays fixed
transform.eulerAngles = cameraRotation;
}
void UpdateCameraPosition(bool smooth)
{
// Calculate height and Z offset based on zoom level
float height = Mathf.Lerp(minZoomHeight, maxZoomHeight, zoomLevel);
float zOffset = -Mathf.Lerp(minZoomHeight * zoomZRatio, maxZoomHeight * zoomZRatio, zoomLevel);
// Create the target position
Vector3 targetPosition = target.position + new Vector3(0, height, zOffset);
if (smooth)
{
// Smoothly move towards the target position
transform.position = Vector3.Lerp(transform.position, targetPosition, followSpeed * Time.deltaTime);
}
else
{
// Instantly set position
transform.position = targetPosition;
}
}
}