77 lines
2.4 KiB
C#
77 lines
2.4 KiB
C#
using UnityEngine;
|
|
using DG.Tweening;
|
|
|
|
public class LineSegment : MonoBehaviour
|
|
{
|
|
public Vector3 StartPoint { get; private set; }
|
|
public Vector3 EndPoint { get; private set; }
|
|
public Transform start;
|
|
public Transform end;
|
|
|
|
private LineRenderer lineRenderer;
|
|
private BoxCollider2D boxCollider;
|
|
|
|
private void Awake()
|
|
{
|
|
lineRenderer = GetComponent<LineRenderer>();
|
|
boxCollider = GetComponent<BoxCollider2D>();
|
|
}
|
|
|
|
private void Start()
|
|
{
|
|
if (start != null && end != null)
|
|
{
|
|
Initialize(start.position, end.position);
|
|
}
|
|
}
|
|
|
|
public void Initialize(Vector3 startPoint, Vector3 endPoint)
|
|
{
|
|
StartPoint = startPoint;
|
|
EndPoint = endPoint;
|
|
|
|
lineRenderer.positionCount = 2;
|
|
lineRenderer.SetPosition(0, StartPoint);
|
|
lineRenderer.SetPosition(1, EndPoint);
|
|
|
|
// Calculate the length of the line segment
|
|
float length = Vector3.Distance(StartPoint, EndPoint);
|
|
|
|
// Calculate the direction of the line segment
|
|
Vector3 direction = (EndPoint - StartPoint).normalized;
|
|
|
|
// Set the size of the BoxCollider2D
|
|
boxCollider.size = new Vector2(length, 0.6f); // Change 0.1f to the desired thickness of the line
|
|
|
|
// Set the center of the BoxCollider2D
|
|
boxCollider.offset = new Vector2(length / 2, 0);
|
|
|
|
// Rotate the BoxCollider2D to align with the line segment
|
|
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
|
|
boxCollider.transform.rotation = Quaternion.Euler(0, 0, angle);
|
|
|
|
// Set the position of the BoxCollider2D to the start point
|
|
boxCollider.transform.position = StartPoint;
|
|
}
|
|
|
|
|
|
public void ShrinkAndDisappear()
|
|
{
|
|
// Shrink the line segment from the end to the start
|
|
DOTween.To(() => EndPoint, x => EndPoint = x, StartPoint, 1f)
|
|
.OnUpdate(() => {
|
|
lineRenderer.SetPosition(0, StartPoint);
|
|
lineRenderer.SetPosition(1, EndPoint);
|
|
// Update the BoxCollider2D
|
|
float length = Vector3.Distance(StartPoint, EndPoint);
|
|
Vector3 direction = (EndPoint - StartPoint).normalized;
|
|
boxCollider.size = new Vector2(length, 0.6f); // Change 0.1f to the desired thickness of the line
|
|
boxCollider.offset = new Vector2(length / 2, 0);
|
|
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
|
|
boxCollider.transform.rotation = Quaternion.Euler(0, 0, angle);
|
|
})
|
|
.OnComplete(() => Destroy(gameObject));
|
|
}
|
|
|
|
}
|