Yes, the formula for a normal vector is incorrect. The normal vector is a vector of length one which is perpendicular to the object it is calculated for (line in your case).I'm guessing its how I'm calculating the "wall normal" I'm using L.Seg.Normal (Seg is P2-P1) is this the wrong thing to do?
A function for finding a normal vector for a segment in 2D can be like this
[pascal]
//finds a normal vector to a segment
function NormalVector(seg : TVector) : TVector;
begin
//find vector perpendicular to seg
Result.x := - seg.y;
Result.y := seg.x;
//normalize
Result := Normalize(Result);
end;
[/pascal]
You should also change some code in your test application to correctly display the results.
This is how I have changed the "reflection" part of FormPaint method in Reflect demo.
[pascal]
...
RL:= TVLine.Create;
try
IP := SegmentIntersection2D(L1.P1, L1.P2, L2.P1, L2.P2);
if(IP<>nil)then
begin
//n and len are declared in var section as m : TVector; len : TVectorNumber;
//a normal vector to a segment
n := TVector.Create;
n.X := -l1.seg.Y;
n.Y := L1.seg.X;
//I had to normalize vector "manually" cause I had some problems (segfaults)
//when mixing IVector and TVector
len := n.Length;
n.X := n.X / len;
n.Y := n.Y / Len;
//find a vector to reflect. It is a vector from object position (l2.P1) to incidence point (ip)
s := ip - l2.P1;
//find reflection vector
r := s.ReflectAbout(n);
//and normalize it
r := r.Normal;
//line showing the reflected vector
rl.P1 := ip;
rl.P2 := rl.P1 + 40*r; //I multiplied r by forty to make line long enough to be visible
plotLine(RL, clRed);
plotVector(IP, clBlack);
end;
finally
RL.Free;
...
[/pascal]
Hopefully, this should solve your problem.
Bookmarks