I have a problem in finding the intersection between two lines. The intersecting points are not correct.
Intersection points are computed by solving the equations of the lines. Before solving the equation, I construct the equation of line (of the form y = mx + c) and then use slide rule for solving the equations for finding the intersection points.
I know there are better methods for finding the intersection between two lines. But I want to know whether my approach can be used for finding the intersection and if so, where is my code going wrong.
Following is the code.
text
#include <GL/glut.h>
#include "stdlib.h"
#include <stdio.h>
typedef struct line
{
float x1;
float y1;
float x2;
float y2;
}Lines;
Lines straight_line[2];
float* FormEquation(Lines lin)
{
// y = mx + c;
// y- y1 = m(x-x1);
// mx - y - mx1 + y1 = 0;
float* coeff = new float[3];
float slope = (lin.y2 - lin.y1)/(lin.x2 - lin.x1);
coeff[0] = slope * lin.x1;
coeff[1] = 1;
coeff[2] = -slope * lin.x1 + lin.y1;
return coeff;
}
bool Test_Intersection(Lines line1,Lines line2,float* point)
{
float* coeff1 = FormEquation(line1);
float* coeff2 = FormEquation(line2);
float d = (coeff2[0]*coeff1[1] - coeff1[0]*coeff2[1]);
point[0] = (coeff1[2] * coeff2[0] - coeff2[2] * coeff1[0])/d;
if(d==0)
return false;
point[1] = (coeff1[2] - coeff1[1] * point[0]) / coeff1[0];
return true;
}
void setpoints()
{
straight_line[0].x1 = 1.0;
straight_line[0].y1 = 2.0;
straight_line[0].x2 = 7.0;
straight_line[0].y2 = 6.0;
straight_line[1].x1 = 2.0;
straight_line[1].y1 = 3.0;
straight_line[1].x2 = 6.0;
straight_line[1].y2 = 5.0;
float* point = new float[2];
bool intersection = Test_Intersection(straight_line[0],straight_line[1],point);
if(intersection)
{
printf("Line are intersecting = %f,%f
",point[0],point[1]);
}
else
{
printf("Not intersecting
");
}
}