- Home /
Question by
jsmith09 · Oct 17, 2016 at 09:04 PM ·
collider2danglelinerenderervector2mathf
Adjusting an angle of a collider2D to a linerenderer that is user-created
I am having issues with adjusting the angle of a collider2D to a linerenderer that created by the user. I used this solution: http://www.theappguruz.com/blog/add-collider-to-line-renderer-unity from @Swati Patel but when the collider is switched to a 2D collider, the angle is off. I tried to use a pure math way and tried to get the angle by Acos(vector2*vector2) but that didn’t work. I tried to use Vector2.Angle() but that didn’t work either. What am I doing wrong and how could I fix it? Should I use a different method to render a line? The code is a little messy due to adjusting it multiple times but the first solution is intact.
public void addColliderToLine(GameObject startpoint, GameObject endpoint)
{
Vector2 startpos = startpoint.transform.position;
Vector2 endpos = endpoint.transform.position;
float lenLine = (endpos - startpos).magnitude;
BoxCollider2D col = new GameObject("Collider").AddComponent<BoxCollider2D>();
col.transform.parent = line.transform;
col.size = new Vector3(lenLine, 0.2f);
Vector3 midPoint = (StartPoint.transform.position + EndPoint.transform.position) / 2;
col.transform.position = midPoint;
Vector2 diff = endpos - startpos;
float sign = (endpos.y < startpos.y) ? -1.0f : 1.0f;
float angle = Vector2.Angle(Vector2.right, diff) * sign;
//float angle = (Mathf.Abs(startpos.y - endpos.y) / Mathf.Abs(startpos.x - endpos.x));
//if ((startpos.y < endpos.y && startpos.x > endpos.x) || (endpos.y < startpos.y && endpos.x > startpos.x))
//{
// angle *= -1;
//}
//angle = Mathf.Rad2Deg * Mathf.Atan(angle);
col.transform.Rotate(0, 0, angle);
col.isTrigger = true;
}
Comment