using UnityEngine; using System.Collections; namespace MoreMountains.Tools { /// /// Add this class to an object (usually a sprite) and it'll face the camera at all times /// [AddComponentMenu("More Mountains/Tools/Camera/MMBillboard")] public class MMBillboard : MonoBehaviour { /// the camera we're facing public Camera MainCamera { get; set; } /// whether or not this object should automatically grab a camera on start public bool GrabMainCameraOnStart = true; /// whether or not to nest this object below a parent container public bool NestObject = true; protected GameObject _parentContainer; private Transform _transform; /// /// On awake we grab a camera if needed, and nest our object /// protected virtual void Awake() { _transform = transform; if (GrabMainCameraOnStart == true) { GrabMainCamera (); } } private void Start() { if (NestObject) { NestThisObject(); } } /// /// Nests this object below a parent container /// protected virtual void NestThisObject() { _parentContainer = new GameObject(); _parentContainer.name = "Parent"+transform.gameObject.name; _parentContainer.transform.position = transform.position; transform.parent = _parentContainer.transform; } /// /// Grabs the main camera. /// protected virtual void GrabMainCamera() { MainCamera = Camera.main; } /// /// On update, we change our parent container's rotation to face the camera /// protected virtual void Update() { if (NestObject) { _parentContainer.transform.LookAt(_parentContainer.transform.position + MainCamera.transform.rotation * Vector3.back, MainCamera.transform.rotation * Vector3.up); } else { _transform.LookAt(_transform.position + MainCamera.transform.rotation * Vector3.back, MainCamera.transform.rotation * Vector3.up); } } } }