# How do make a box collider align with a line renderer continuously?

I am having the issue of aligning my BoxCollider2D with my linerenderer.

I am trying to have a laser shoot using:
Physics2D.Linecast(startingPoint.transform.position, maxEndPoint.transform.position);

This works fine and the line is always shooting in the right direction and angle when I rotate the object. But, when I am drawing a box collider, the box doesn't align at the correct position.

Firstly, the boxcollider is attached as a child component of the line renderer.

I am using this code to get the size of the collider, which seems to work fine.

float lineLength = Vector3.Distance(lazer.GetPosition(1), lazer.GetPosition(0));


This code is for aligning the collider with the line renderer. I know I am supposed to get the midpoint, because that's how you control the location of the box collider, but I need to know the math to always make it align.

    lazerCollider.offset = new Vector3(0, ourHitPos.y - startingPoint.transform.position.y, 0) / 2;
lazerCollider.size = new Vector3(lazerWidth, lineLength, 0);


I know right now I am only using the Y coordinate... I just need to know the math to make this work.

• why you just dont use a spriteRenderer instead of Line Renderer? – virtouso Sep 3 '19 at 5:57
• Why do you need the box collider? Physics2D's LineCast, RayCast or BoxCast could come in handy here, so you need to explain the scenario a bit more, why box collider? – Digvijaysinh Gohil Sep 4 '19 at 13:04

To me its looks like every thing is working fine. But the child which is holding the box "BoxCollider2D" is off the center So you need to take one more step to find the the mid point of the laser and then assign it to the child which holds "BoxCollider2D".

Formula for finding mid point is:

• (vector1 + vector2)/2

vector 1, is start point of the laser.

vector 2, is end point of the laser.

or vice versa

So when you expend the formula it will become like:

• (((X1,+X2)/2) , ((Y1,+Y2)/2) , ((Z1,+Z2)/2))
• Hi Swati, Finding the midpoint is easy enough. I have that part already for the y coordinate. If you look at the lazercollider.offset, that is where the issue is. I'm not really certain how it behaves, but the Y coordinate of it seems to be what places the Lazer in weird positions. – Cameron Roberson Sep 3 '19 at 7:12
• Yep you are right. But have you checked that child which holds the collider is at the middle of the laser? and what is "ourHitPos" and "startingPoint" and where are these point situated? is "startingPoint" is start point for line renderer? – Swati Sep 3 '19 at 7:23
• At the second image child looks like off center... – Swati Sep 3 '19 at 7:31