105 lines
2.6 KiB
C#
105 lines
2.6 KiB
C#
using UnityEngine;
|
|
using UnityEngine.Serialization;
|
|
|
|
[RequireComponent(typeof(PhysicLineSegment))]
|
|
public class PhysicCable : MonoBehaviour
|
|
{
|
|
[FormerlySerializedAs("StartTranform")] public Transform startTransform;
|
|
|
|
public PhysicLineSegment physicLine;
|
|
|
|
private Transform targetTransform;
|
|
private bool isEnabled;
|
|
|
|
// Start is called before the first frame update
|
|
void Start()
|
|
{
|
|
EnsurePhysicLine();
|
|
}
|
|
|
|
public void Init(Vector3 endPos)
|
|
{
|
|
EnsurePhysicLine();
|
|
if (physicLine == null || startTransform == null) return;
|
|
|
|
physicLine.Initialize(startTransform.position, endPos, GetOutletDirection(endPos));
|
|
}
|
|
|
|
public void HideCable()
|
|
{
|
|
GetComponent<LineRenderer>().enabled = false;
|
|
}
|
|
|
|
public void ShowCable()
|
|
{
|
|
GetComponent<LineRenderer>().enabled = true;
|
|
}
|
|
|
|
public void SetEnabled(bool enabled)
|
|
{
|
|
isEnabled = enabled;
|
|
GetComponent<LineRenderer>().enabled = enabled;
|
|
}
|
|
|
|
public void SetTarget(Transform target)
|
|
{
|
|
targetTransform = target;
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
if (isEnabled)
|
|
{
|
|
EnsurePhysicLine();
|
|
if (physicLine == null) return;
|
|
|
|
// 更新起点位置
|
|
if (startTransform != null)
|
|
{
|
|
Vector3 fallbackTarget = targetTransform != null ? targetTransform.position : startTransform.position + startTransform.right;
|
|
physicLine.UpdateOutletDirection(GetOutletDirection(fallbackTarget));
|
|
physicLine.UpdateStart(startTransform.position);
|
|
}
|
|
|
|
// 更新终点位置
|
|
if (targetTransform != null)
|
|
{
|
|
physicLine.UpdatePlug(targetTransform);
|
|
}
|
|
}
|
|
}
|
|
|
|
private Vector3 GetOutletDirection(Vector3 fallbackTarget)
|
|
{
|
|
if (startTransform == null)
|
|
{
|
|
return Vector3.right;
|
|
}
|
|
|
|
if (startTransform.parent != null)
|
|
{
|
|
Vector3 radialDirection = startTransform.position - startTransform.parent.position;
|
|
if (radialDirection.sqrMagnitude > 1e-6f)
|
|
{
|
|
return radialDirection.normalized;
|
|
}
|
|
}
|
|
|
|
Vector3 fallbackDirection = fallbackTarget - startTransform.position;
|
|
if (fallbackDirection.sqrMagnitude > 1e-6f)
|
|
{
|
|
return fallbackDirection.normalized;
|
|
}
|
|
|
|
return startTransform.right;
|
|
}
|
|
|
|
private void EnsurePhysicLine()
|
|
{
|
|
if (physicLine == null)
|
|
{
|
|
physicLine = transform.GetComponent<PhysicLineSegment>();
|
|
}
|
|
}
|
|
}
|