72 lines
2.0 KiB
C#
72 lines
2.0 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
[RequireComponent(typeof(LineRenderer))]
|
|
public class Cable : MonoBehaviour
|
|
{
|
|
public Transform start;
|
|
private Transform end;
|
|
|
|
public Transform End
|
|
{
|
|
get { return end; }
|
|
set { end = value; }
|
|
}
|
|
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;
|
|
}
|
|
}
|
|
}
|
|
} |