Hey guys,
So my Maths has obviously gotten a little rusty and I seem to be struggling with what should be quite simple....
The scenario:
I have lines being drawn in 3D space that are calculated using an algorithm. These lines are actually made up of multiple line segments to create what looks like a single smooth curved line. I don't know where the lines will be drawn, in what direction etc. but I can grab the points on the line once the line object has been created. These lines are inside a cylinder and at some point may/may not intersect/collide with part of the cylinder.
The Task:
I have to mark exactly (or at least as close to exact as possible) the point at which a line intersects with part of the cylinder.
NB: I would appreciate if you ignored the z. This is quite easy to deal with on its own. i.e. collisions with the ends of the cylinder.
It is easy enough to single out the individual line segments which actually intersect with the radius of the cylinder. So this leaves me with (in effect) a 2D style calculation; determining exactly where a line intersects a circle.
A quick look on google and I find a good solution but, (and this is the problem) I don't fully understand the equations used because the website if very brief.
I have created a code version of the formula and it works perfectly well but only for some/most of my line objects. I think I know the reason for this but I don't fully understand the calculations used and hence can't solve this for myself.
The formula that I used can be found here
If you follow the link you will see that the formula uses:
x = Ddy +/- ...blah...
y = -Ddx +/- ...blah...
I basically need to know when I should be adding and when I should be subtracting. Currently I am only ever adding which is obviously why my code isn't quite working. I tried determining the direction of the line and adding/subtracting based on that but to no avail.
My Code:
// Definitions
float x, y;
float dx = p2.fX - p1.fX;
float dy = p2.fY - p1.fY;
float dr = sqrt( ( dx * dx ) + ( dy * dy ) );
float D = ( ( p1.fX * p2.fY ) + ( p2.fX * p1.fY ) );
float rtDescrim = sqrt( ( ( r * r ) * ( dr * dr ) ) - ( D * D ) );
x = ( D * dy ) + ( ( sgn(dy) * dx ) * rtDescrim );
x /= ( dr * dr );
y = ( -D * dx ) + ( fabs( dy ) * rtDescrim );
y /= ( dr * dr );
TEveVector result = TEveVector( x, y, 0.001 );
return result;
Any help would be greatly appreciated :)