You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.6 KiB
C#

using UnityEngine;
using System.Collections.Generic;
public class LineColliderCapsules : MonoBehaviour
{
public LineRenderer lineRenderer;
public float colliderRadius = 0.1f; // Adjust based on line width
private List<GameObject> colliders = new List<GameObject>();
private void Start()
{
GenerateColliders();
}
private void Update()
{
UpdateColliders();
}
private void GenerateColliders()
{
// Destroy old colliders
foreach (var col in colliders)
{
Destroy(col);
}
colliders.Clear();
if (lineRenderer.positionCount < 2) return;
for (int i = 0; i < lineRenderer.positionCount - 1; i++)
{
GameObject colObj = new GameObject("LineSegmentCollider");
colObj.transform.parent = transform;
CapsuleCollider capsule = colObj.AddComponent<CapsuleCollider>();
capsule.radius = colliderRadius;
capsule.height = Vector3.Distance(lineRenderer.GetPosition(i), lineRenderer.GetPosition(i + 1));
capsule.direction = 2; // Z-axis
colliders.Add(colObj);
}
UpdateColliders();
}
private void UpdateColliders()
{
if (lineRenderer.positionCount < 2) return;
for (int i = 0; i < colliders.Count; i++)
{
Vector3 start = lineRenderer.GetPosition(i);
Vector3 end = lineRenderer.GetPosition(i + 1);
Vector3 midPoint = (start + end) / 2;
colliders[i].transform.position = midPoint;
colliders[i].transform.LookAt(end);
}
}
}