I have been looking at how to reflect a point in a line, and found this question which seems to do the trick, giving this formula to calculate the reflected point:
Given (x,y) and a line y = ax + c we want the point (x', y') reflected on the line.
Set d:= (x + (y - c)*a)/(1 + a^2)
Then x' = 2*d - x
and y' = 2*d*a - y + 2c
However there are two problems with this implementation for my needs:
- My line is not described in the form
y = ax + c
(so I'd have to translate it, which is easy to do, but it means the process is slower). - What if
a
is infinity ie. a vertical line?
Is there a simple way to calculate (x', y')
, the reflection of point (x, y)
in a line, where the line is described by the two points (x1, y1)
and (x2, y2)
?
Edit:
I've found a formula which does this, but it seems as though it does not work with lines that look like they have equation y = x.
Here it is in actionscript:
public static function reflect(p:Point, l:Line):Point
{
// (l.sx, l.sy) = start of line
// (l.ex, l.ey) = end of line
var dx:Number = l.ex - l.sx;
var dy:Number = l.ey - l.sy;
if ((dx == 0) && (dy == 0))
{
return new Point(2 * l.sx - p.x, 2 * l.sy - p.y);
}
else
{
var t:Number = ((p.x - l.sx) * dx + (p.y - l.sy) * dy) / (dx * dx + dy * dy);
var x:Number = 2 * (l.sx + t * dx) - p.x;
var y:Number = 2 * (l.sy + t * dy) - p.y;
return new Point(x, y);
}
}
Does anyone have any idea where this formula goes wrong? I am still happy to take other solutions than the above formula - anything that'll work!