- Home /
Adding a collider to a line renderer
I have a line renderer that can be resized and rotated by dragging either ends. I also have to be able to move it around by dragging somewhere inside the bounds of the line renderer. I used to do this with a sprite and it worked fine but it made it complicated for nothing so I switched to a line renderer which simplified everything.
Everything works fine except for moving it around. The collider I used to use followed the sprite around but now that I'm using a line renderer, it doesn't anymore. How should I go around implementing such a collider for a line renderer. I'm using Unity's default line renderer, nothing custom or from the asset store.
Answer by eplante · Aug 08, 2019 at 07:14 PM
I figured out my problem. My initial solution was the right one but it didn't work because I was inputing an angle in degrees to Mathf.cos and sin but those functions require radians. My solution is the following, just basic trigonometry to find the corners of the line and assign those to a polygon collider.
float cos = (lineRend.startWidth / 2) * Mathf.Cos((90f - angle) * Mathf.Deg2Rad);
float sin = (lineRend.startWidth / 2) * Mathf.Sin((90f - angle) * Mathf.Deg2Rad);
Vector2[] points = new Vector2[4];
points[0] = startPos + new Vector3(-cos, sin);
points[1] = startPos + new Vector3(cos, -sin);
points[2] = endPos - new Vector3(-cos, sin);
points[3] = endPos - new Vector3(cos, -sin);
polyCol.SetPath(0, points);