- Home /
Add a BoxCollider2D to LineRenderer
Hi,
I've got some code that draws straight, angled rectangles on screen whilst the mouse button is pressed using LineRenderer. However I need to detect (but not stop) when any of these rectangles collide. I imagine that I need to add a BoxCollider2D (and maybe a RigidBody2d) to the gameobject that matches the dimensions and rotation of the line renderer but I can't figure out how to go about it.
Here is what my code does so far:
private LineRenderer lineRenderer;
public GameObject LinePrefab;
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
GameObject lineObject = Instantiate(LinePrefab) as GameObject;
lineRenderer = lineObject.AddComponent<LineRenderer>();
lineRenderer.SetVertexCount(2);
Vector3 mousePos = Input.mousePosition;
mousePos.z = 1.0f;
Vector3 worldPos = Camera.main.ScreenToWorldPoint(mousePos);
lineRenderer.SetPosition(0, worldPos);
}
if (Input.GetKey(KeyCode.Mouse0))
{
Vector3 mousePos = Input.mousePosition;
mousePos.z = 1.0f;
Vector3 worldPos = Camera.main.ScreenToWorldPoint(mousePos);
lineRenderer.SetPosition(1, worldPos);
}
}
Here are two solutions, one using Linecast, and one using colliders. They are for a TrailRenderer, but it shouldn't take too much to adapt them to a LineRenderer:
http://answers.unity3d.com/questions/418759/how-might-i-go-about-making-a-trail-render-that-de.html
http://answers.unity3d.com/questions/285040/draw-a-line-in-game.html
Your answer
![](https://koobas.hobune.stream/wayback/20220613131027im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Best way to place a Line Renderer into scene... 1 Answer
Unity Line Animation 0 Answers
Erasing part of line renderer 0 Answers
What's the best way to draw a 2D line WITHOUT using LineRenderer? 1 Answer
Clipping Errors with LineRenderer? 0 Answers