Skip to content

Instantly share code, notes, and snippets.

@nailuj05
Created September 9, 2021 21:01
Show Gist options
  • Save nailuj05/ea0e07fe8e70cbe0fac71e3733cc1a4d to your computer and use it in GitHub Desktop.
Save nailuj05/ea0e07fe8e70cbe0fac71e3733cc1a4d to your computer and use it in GitHub Desktop.
A simple way to add a collider to a Unity LineRenderer, intended for 2D use, can be adapted to 3D aswell!
using UnityEngine;
[RequireComponent(typeof(BoxCollider2D), typeof(LineRenderer))]
public class LineCollider : MonoBehaviour
{
private LineRenderer lineRenderer;
private BoxCollider2D boxCollider;
void Awake()
{
lineRenderer = GetComponent<LineRenderer>();
boxCollider = GetComponent<BoxCollider2D>();
}
void Update()
{
var dir = lineRenderer.GetPosition(0) - lineRenderer.GetPosition(1);
var center = (lineRenderer.GetPosition(0) + lineRenderer.GetPosition(1)) / 2;
var width = (lineRenderer.startWidth + lineRenderer.endWidth) / 2;
var length = dir.magnitude;
//Apply Rotation
transform.right = dir;
transform.eulerAngles.Set(0, 0, transform.eulerAngles.z);
//Apply Position
transform.position = center;
//Scale Collider
boxCollider.size = new Vector2(length, width) * 1 / transform.lossyScale;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment