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:
y = ax + c
(so I'd have to translate it, which is easy to do, but it means the process is slower).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)
?
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!
Find the normal vector from the point onto the line and add it twice to the point. See wikipedia for the formula.
If you express everything in vectors you won't have the problems with an infinite slope.
;; line defined by ax+by+c=0
;; normal (a b) and distance from origin -c
(defun reflect-point-on-line (a b c px py)
(/ (+ (* a px)
(* b py)
c)
(sqrt (+ (expt a 2) (expt b 2)))))
#+nil ;; y-axis to (2 1)
(reflect-point-on-line 1 0 0 2 1) ;; => 2
#+nil ;; x-axis to (4 5)
(reflect-point-on-line 0 1 0 4 5) ;; => 5