60 lines
1.8 KiB
C#
60 lines
1.8 KiB
C#
using UnityEngine;
|
|
|
|
public class BgmGyroRotator : MonoBehaviour
|
|
{
|
|
public RectTransform target;
|
|
public float maxRotation = 3f;
|
|
public float rotX = 1f;
|
|
public float rotY = 1f;
|
|
public float rotZ = 0.35f;
|
|
public float smooth = 8f;
|
|
public bool useUnscaled = true;
|
|
|
|
private Quaternion baseRotation;
|
|
private bool baseCaptured = false;
|
|
|
|
private void Awake()
|
|
{
|
|
if (target == null) target = transform as RectTransform;
|
|
CaptureBase();
|
|
}
|
|
|
|
private void OnEnable()
|
|
{
|
|
if (target == null) target = transform as RectTransform;
|
|
CaptureBase();
|
|
}
|
|
|
|
private void CaptureBase()
|
|
{
|
|
if (target == null) return;
|
|
baseRotation = target.localRotation;
|
|
baseCaptured = true;
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
if (target == null) return;
|
|
if (!baseCaptured) CaptureBase();
|
|
|
|
Vector2 norm = GetMouseNormalized();
|
|
Vector3 delta = new Vector3(-norm.y * maxRotation * rotX,
|
|
norm.x * maxRotation * rotY,
|
|
norm.x * maxRotation * rotZ);
|
|
Quaternion targetRot = baseRotation * Quaternion.Euler(delta);
|
|
float dt = useUnscaled ? Time.unscaledDeltaTime : Time.deltaTime;
|
|
float t = 1f - Mathf.Exp(-Mathf.Max(0.01f, smooth) * dt);
|
|
target.localRotation = Quaternion.Slerp(target.localRotation, targetRot, t);
|
|
}
|
|
|
|
private static Vector2 GetMouseNormalized()
|
|
{
|
|
Vector2 pos = Input.mousePosition;
|
|
if (Screen.width <= 1 || Screen.height <= 1)
|
|
return Vector2.zero;
|
|
float x = (pos.x / Screen.width) * 2f - 1f;
|
|
float y = (pos.y / Screen.height) * 2f - 1f;
|
|
return new Vector2(Mathf.Clamp(x, -1f, 1f), Mathf.Clamp(y, -1f, 1f));
|
|
}
|
|
}
|