84 lines
2.0 KiB
C#
84 lines
2.0 KiB
C#
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
[RequireComponent(typeof(LineRenderer))]
|
|
public class PhysicLineSegment : MonoBehaviour
|
|
{
|
|
public float segmentSpacing = 0.1f;
|
|
public int k = 30;
|
|
|
|
public Vector3 start;
|
|
public Vector3 end;
|
|
|
|
private List<VerletParticle> particles = new List<VerletParticle>();
|
|
private List<VerletStick> sticks = new List<VerletStick>();
|
|
private LineRenderer lineRenderer;
|
|
private int segmentCount;
|
|
public float gravity = -9.8f;
|
|
|
|
public void Initialize(Vector3 start, Vector3 end)
|
|
{
|
|
this.start = start;
|
|
this.end = end;
|
|
//originalLength = Vector3.Distance(start, end);
|
|
|
|
// Calculate the number of segments and the spacing between them
|
|
segmentCount = Mathf.RoundToInt(Vector3.Distance(start, end) / segmentSpacing);
|
|
lineRenderer = GetComponent<LineRenderer>();
|
|
|
|
// Initialize particles
|
|
for (int i = 0; i < segmentCount; i++)
|
|
{
|
|
// Calculate the position of the segment
|
|
var particle = new VerletParticle(Vector3.Lerp(start, end, i / (float)segmentCount));
|
|
|
|
particles.Add(particle);
|
|
}
|
|
|
|
// Initialize sticks
|
|
for (int i = 0; i < segmentCount - 1; i++)
|
|
{
|
|
sticks.Add(new VerletStick(particles[i], particles[i + 1], segmentSpacing));
|
|
}
|
|
|
|
// Lock the first particle
|
|
particles[0].isLocked = true;
|
|
|
|
lineRenderer.positionCount = segmentCount;
|
|
}
|
|
|
|
|
|
void FixedUpdate()
|
|
{
|
|
UpdateLine();
|
|
for (int i = 0; i < segmentCount; i++)
|
|
{
|
|
lineRenderer.SetPosition(i, particles[i].position);
|
|
}
|
|
}
|
|
|
|
void UpdateLine()
|
|
{
|
|
// Apply gravity to particles
|
|
for (int i = 1; i < particles.Count; i++)
|
|
{
|
|
|
|
particles[i].ApplyForce(Vector3.up * gravity * Time.deltaTime);
|
|
particles[i].UpdatePosition(Time.deltaTime);
|
|
}
|
|
|
|
// Update sticks
|
|
for (int ik = 0; ik < k; ik++)
|
|
{
|
|
foreach (var stick in sticks)
|
|
{
|
|
stick.UpdateStick();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|