88 lines
3.2 KiB
C#
88 lines
3.2 KiB
C#
using UnityEngine;
|
||
|
||
namespace AibisDream.FixSystem
|
||
{
|
||
public class CableReel : MonoBehaviour
|
||
{
|
||
[Header("转盘设置")]
|
||
[SerializeField] private float torqueStrength = 200f; // 扭矩强度
|
||
[SerializeField] private float angularDamping = 5f; // 角速度阻尼
|
||
|
||
private CableSystem cableSystem;
|
||
private float angularVelocity; // 角速度
|
||
private float currentAngle; // 当前角度
|
||
public Vector3 outletPos { get; private set; } // 出线口位置
|
||
private SpriteRenderer spriteRenderer;
|
||
private float reelRadius; // 转盘半径
|
||
|
||
private void Start()
|
||
{
|
||
// 获取CableSystem引用
|
||
cableSystem = transform.parent.GetComponent<CableSystem>();
|
||
currentAngle = transform.eulerAngles.z;
|
||
|
||
// 获取SpriteRenderer并计算半径
|
||
spriteRenderer = GetComponent<SpriteRenderer>();
|
||
if (spriteRenderer != null)
|
||
{
|
||
// 使用sprite的bounds来计算半径
|
||
reelRadius = spriteRenderer.bounds.extents.y; // 使用y方向的半高作为半径
|
||
}
|
||
else
|
||
{
|
||
Debug.LogWarning("CableReel没有SpriteRenderer组件!");
|
||
reelRadius = 0.5f; // 默认值
|
||
}
|
||
|
||
// 初始化出线口位置
|
||
UpdateOutletPosition();
|
||
}
|
||
|
||
private void UpdateOutletPosition()
|
||
{
|
||
// 更新出线口位置(圆形本地坐标 (0, -radius) 转成世界坐标)
|
||
outletPos = transform.TransformPoint(new Vector3(0, -reelRadius, 0));
|
||
}
|
||
|
||
public void ResetRotation()
|
||
{
|
||
// 重置角度和角速度
|
||
currentAngle = 0;
|
||
angularVelocity = 0;
|
||
transform.rotation = Quaternion.identity;
|
||
UpdateOutletPosition();
|
||
}
|
||
|
||
public void UpdateRotation()
|
||
{
|
||
// 如果PhysicCable激活,不进行旋转
|
||
if (cableSystem == null || cableSystem.PlugRef == null ||
|
||
cableSystem.PhysicCableRef.GetComponent<LineRenderer>().enabled) return;
|
||
|
||
Vector2 center = transform.position;
|
||
|
||
// 使用当前出线口位置
|
||
Vector2 outlet = outletPos;
|
||
|
||
// 力向量(线缆拉力方向)
|
||
Vector2 force = (Vector2)cableSystem.PlugRef.transform.position - outlet;
|
||
|
||
// 杆臂向量(力作用点相对于圆心的位置)
|
||
Vector2 r = outlet - center;
|
||
|
||
// 计算 2D 扭矩:r × F
|
||
float torque = (r.x * force.y - r.y * force.x);
|
||
|
||
// 应用扭矩 + 阻尼
|
||
angularVelocity += torque * torqueStrength * Time.deltaTime;
|
||
angularVelocity *= Mathf.Exp(-angularDamping * Time.deltaTime); // 简易阻尼
|
||
|
||
// 应用旋转
|
||
currentAngle += angularVelocity * Time.deltaTime;
|
||
transform.rotation = Quaternion.Euler(0, 0, currentAngle);
|
||
|
||
// 更新出线口位置
|
||
UpdateOutletPosition();
|
||
}
|
||
}
|
||
} |