Created
September 9, 2021 21:01
-
-
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!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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