Advertisement
Haze_E1

FaceCamera Script for Unity

Nov 23rd, 2024
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.94 KB | Gaming | 0 0
  1. using UnityEngine;
  2.  
  3. public class FaceCamera : MonoBehaviour
  4. {
  5.     private Camera _mainCamera;
  6.     private Vector3 _offsetFromParent;
  7.  
  8.     private void Start()
  9.     {
  10.         _mainCamera = Camera.main;
  11.  
  12.         // Calculate the initial offset above the cube's position
  13.         _offsetFromParent = transform.localPosition;
  14.     }
  15.  
  16.     private void LateUpdate()
  17.     {
  18.         // Maintain the position offset above the parent
  19.         transform.position = transform.parent.position + _offsetFromParent;
  20.  
  21.         // Make the canvas face the camera
  22.         Vector3 directionToCamera = _mainCamera.transform.position - transform.position;
  23.         directionToCamera.y = 0;  // Keep the text upright
  24.  
  25.         // Apply rotation to face the camera
  26.         if (directionToCamera == Vector3.zero) return;
  27.         Quaternion targetRotation = Quaternion.LookRotation(-directionToCamera, Vector3.up);
  28.         transform.rotation = targetRotation;
  29.     }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement