52 lines
1.6 KiB
C#
52 lines
1.6 KiB
C#
using Unity.Cinemachine;
|
|
using UnityEngine;
|
|
|
|
[ExecuteAlways]
|
|
public class LookAtCamera : MonoBehaviour
|
|
{
|
|
public enum LookMode
|
|
{
|
|
LookAt, // Nhìn trực tiếp vào camera
|
|
LookAway, // Quay mặt cùng hướng với camera (ngược lại)
|
|
OnlyYAxis // Chỉ xoay theo trục Y (thường dùng cho UI trên mặt đất)
|
|
}
|
|
|
|
[Tooltip("Camera mà object này sẽ hướng tới. Nếu bỏ trống sẽ tự tìm main camera.")]
|
|
public Camera targetCamera;
|
|
|
|
[Tooltip("Kiểu xoay theo hướng camera.")]
|
|
public LookMode mode = LookMode.LookAt;
|
|
|
|
void LateUpdate()
|
|
{
|
|
if (targetCamera == null)
|
|
{
|
|
var brain = FindFirstObjectByType<CinemachineBrain>();
|
|
if (brain != null)
|
|
targetCamera = brain.OutputCamera;
|
|
if (targetCamera == null && Camera.main != null)
|
|
targetCamera = Camera.main;
|
|
}
|
|
if (targetCamera == null)
|
|
return;
|
|
|
|
switch (mode)
|
|
{
|
|
case LookMode.LookAt:
|
|
transform.LookAt(targetCamera.transform);
|
|
break;
|
|
|
|
case LookMode.LookAway:
|
|
transform.rotation = Quaternion.LookRotation(-targetCamera.transform.forward);
|
|
break;
|
|
|
|
case LookMode.OnlyYAxis:
|
|
Vector3 dir = targetCamera.transform.position - transform.position;
|
|
dir.y = 0; // giữ nguyên trục Y
|
|
if (dir.sqrMagnitude > 0.001f)
|
|
transform.rotation = Quaternion.LookRotation(dir);
|
|
break;
|
|
}
|
|
}
|
|
}
|