38 lines
1.2 KiB
C#
38 lines
1.2 KiB
C#
using UnityEngine;
|
|
|
|
namespace BulletHellTemplate
|
|
{
|
|
/// <summary>
|
|
/// Makes a canvas always face the main camera, respecting all rotations to prevent visual jitter.
|
|
/// Designed for top-down games with world-space canvases.
|
|
/// </summary>
|
|
public class LookAtCamera : MonoBehaviour
|
|
{
|
|
private Transform mainCameraTransform; // Cache the transform of the main camera for efficiency
|
|
|
|
void Start()
|
|
{
|
|
// Cache the main camera transform
|
|
if (Camera.main != null)
|
|
{
|
|
mainCameraTransform = Camera.main.transform;
|
|
}
|
|
}
|
|
|
|
void LateUpdate()
|
|
{
|
|
if (mainCameraTransform != null)
|
|
{
|
|
// Calculate the direction vector from the canvas to the camera
|
|
Vector3 directionToCamera = mainCameraTransform.position - transform.position;
|
|
|
|
// Create a rotation that points the canvas directly at the camera
|
|
Quaternion targetRotation = Quaternion.LookRotation(directionToCamera, Vector3.up);
|
|
|
|
// Apply the rotation to the canvas
|
|
transform.rotation = targetRotation;
|
|
}
|
|
}
|
|
}
|
|
}
|