Files
aibis-dream/Assets/Scripts/FixSystem/Cable/Cable.cs
T
2024-08-23 01:46:57 +08:00

66 lines
1.9 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(LineRenderer))]
public class Cable : MonoBehaviour
{
public Transform start;
public Transform end;
public int resolution = 10;
public float dstMin = 0.1f;
public float dstMax = 1.0f;
public float forceMin = 0.1f;
public float forceMax = 1.0f;
public int k = 10;
private LineRenderer lineRenderer;
private Vector3[] points;
private void Start()
{
lineRenderer = GetComponent<LineRenderer>();
points = new Vector3[resolution];
for (int i = 0; i < resolution; i++)
{
float t = i / (float)(resolution - 1);
points[i] = Vector3.Lerp(start.position, end.position, t);
}
lineRenderer.positionCount = resolution;
}
private void FixedUpdate()
{
UpdateRope();
for (int i = 0; i < resolution; i++)
{
lineRenderer.SetPosition(i, points[i] + Vector3.forward * -.3f);
}
}
void UpdateRope()
{
float t = Mathf.InverseLerp(dstMin, dstMax, (start.position - end.position).magnitude);
float F = Mathf.Lerp(forceMin, forceMax, t);
points[0] = start.position;
points[points.Length - 1] = end.position;
for (int ik = 0; ik < k; ik++)
{
for (int i = 1; i < points.Length - 1; i++)
{
Vector3 offsetPrev = (points[i - 1] - points[i]);
Vector3 offsetNext = points[i + 1] - points[i];
Vector3 velocity = offsetPrev.normalized * offsetPrev.magnitude * F +
offsetNext.normalized * offsetNext.magnitude * F;
points[i] += velocity * Time.deltaTime / k;
}
for (int i = 1; i < points.Length - 1; i++)
{
points[i] += Vector3.down * 9.8f * Time.deltaTime / k;
}
}
}
}