90 lines
2.6 KiB
Plaintext
90 lines
2.6 KiB
Plaintext
using System;
|
||
using UnityEngine;
|
||
using UnityEngine.EventSystems;
|
||
|
||
public class RotateImage : MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler
|
||
{
|
||
private Vector2 preMousePostion;
|
||
private float currAngle;
|
||
private float targetAngle;
|
||
private float originaleAngle;
|
||
|
||
[SerializeField]
|
||
private float rotationSpeed = 4f; // 旋转速度
|
||
|
||
[SerializeField]
|
||
private float returnSpeed = 5f; // 回归速度
|
||
|
||
[SerializeField]
|
||
[Range(0f, 0.5f)]
|
||
private float m_maxDragLength = 0.2f;
|
||
|
||
private float originaleAngleFixed = 90f; // 最大旋转角度限制
|
||
private Action<float> ratateAc;
|
||
private Action<float> m_dragEnd;
|
||
|
||
[SerializeField]
|
||
private float m_maxDeg = 30;
|
||
|
||
[SerializeField]
|
||
private RectTransform m_rotateTransform;
|
||
|
||
public void Init(Action<float> ratateAction, Action<float> dragEnd)
|
||
{
|
||
this.m_dragEnd = dragEnd;
|
||
ratateAc = ratateAction;
|
||
originaleAngle = originaleAngleFixed;
|
||
currAngle = originaleAngle;
|
||
targetAngle = originaleAngle;
|
||
}
|
||
|
||
public void ResetStatu()
|
||
{
|
||
currAngle = originaleAngleFixed;
|
||
targetAngle = originaleAngleFixed;
|
||
originaleAngle = originaleAngleFixed;
|
||
}
|
||
|
||
private float GetRatio()
|
||
{
|
||
return (currAngle - originaleAngleFixed) / m_maxDeg * -1;
|
||
}
|
||
|
||
void Update()
|
||
{
|
||
currAngle = Mathf.Lerp(currAngle,targetAngle,Time.unscaledDeltaTime * 10f);
|
||
m_rotateTransform.localEulerAngles = Vector3.Lerp(m_rotateTransform.localEulerAngles, new Vector3(0, 0, currAngle), Time.unscaledDeltaTime * 10f);
|
||
|
||
// 在拖拽结束后,平滑过渡角度回到0度
|
||
//if (!isDragging && Mathf.Abs(targetAngle - originaleAngle) > 0.1f)
|
||
//{
|
||
// targetAngle = Mathf.Lerp(targetAngle, originaleAngle, Time.unscaledDeltaTime * returnSpeed);
|
||
//}
|
||
ratateAc?.Invoke(GetRatio());
|
||
}
|
||
|
||
public void OnPointerDown(PointerEventData eventData)
|
||
{
|
||
preMousePostion = eventData.position;
|
||
currAngle = targetAngle;
|
||
}
|
||
|
||
public void OnDrag(PointerEventData eventData)
|
||
{
|
||
float maxDragHalfLength = Screen.width * m_maxDragLength;
|
||
float fullLength = maxDragHalfLength * 2;
|
||
|
||
float xoffset = (eventData.position - preMousePostion).x;
|
||
float t = (xoffset + maxDragHalfLength) / fullLength;
|
||
|
||
// 限制角度范围在左右各30度
|
||
targetAngle = Mathf.Lerp(90 + m_maxDeg, 90 - m_maxDeg, t);
|
||
}
|
||
|
||
public void OnPointerUp(PointerEventData eventData)
|
||
{
|
||
targetAngle = originaleAngleFixed;
|
||
m_dragEnd?.Invoke(GetRatio());
|
||
}
|
||
}
|