61 lines
2.0 KiB
C#
61 lines
2.0 KiB
C#
using UnityEngine;
|
||
|
||
namespace IndianOceanAssets.Engine2_5D
|
||
{
|
||
/// <summary>
|
||
/// 场景物件面向摄像机脚本(饥荒风格)。
|
||
/// 让物体始终朝摄像机方向旋转,默认只绕 Y 轴(保持竖直不倒)。
|
||
///
|
||
/// 用法:挂到需要面向摄像机的精灵/物件上即可。
|
||
/// 适合:树木、岩石、角色、道具等 2D 精灵在 3D 场景中的朝向修正。
|
||
/// </summary>
|
||
public class BillboardSprite : MonoBehaviour
|
||
{
|
||
[Tooltip("只绕Y轴旋转(饥荒风格,保持竖直不倒)。关闭则完全面向摄像机。")]
|
||
[SerializeField] private bool lockYAxis = true;
|
||
|
||
[Tooltip("平滑旋转(lerp过渡),关闭则瞬间转向")]
|
||
[SerializeField] private bool smoothRotation = false;
|
||
|
||
[Tooltip("平滑旋转速度")]
|
||
[SerializeField] private float rotationSpeed = 8f;
|
||
|
||
private Camera _mainCamera;
|
||
private Transform _camTransform;
|
||
|
||
private void Start()
|
||
{
|
||
_mainCamera = Camera.main;
|
||
if (_mainCamera != null)
|
||
_camTransform = _mainCamera.transform;
|
||
}
|
||
|
||
private void LateUpdate()
|
||
{
|
||
if (_camTransform == null)
|
||
{
|
||
// 摄像机丢失时重新获取(场景切换等情况)
|
||
_mainCamera = Camera.main;
|
||
if (_mainCamera != null)
|
||
_camTransform = _mainCamera.transform;
|
||
if (_camTransform == null) return;
|
||
}
|
||
|
||
Vector3 dir = _camTransform.position - transform.position;
|
||
|
||
if (lockYAxis)
|
||
dir.y = 0f; // 保持竖直
|
||
|
||
if (dir.sqrMagnitude < 0.0001f) return;
|
||
|
||
Quaternion targetRot = Quaternion.LookRotation(dir);
|
||
|
||
if (smoothRotation)
|
||
transform.rotation = Quaternion.Slerp(transform.rotation, targetRot,
|
||
rotationSpeed * Time.deltaTime);
|
||
else
|
||
transform.rotation = targetRot;
|
||
}
|
||
}
|
||
}
|