Position a node at right angles relative to a line with Python

This code does it:

import math

def movePoint(x1, y1, x2, y2, t, offset):
	angle = math.atan2(y2 - y1, x2 - x1)
	tx = x1 + (x2 - x1) * t
	ty = y1 + (y2 - y1) * t
	dx = math.sin(angle) * offset
	dy = math.cos(angle) * offset
	return NSMakePoint(tx + dx, ty - dy)

position = movePoint(P1.x, P1.y, P2.x, P2.y, 1, 10)
P3.x = position.x
P3.y = position.y

I have added an extra parameter t to the function that lets you decide where on the line from P1 to P2 you want to offset the new point. Set t = 0 to offset P1, set t = 1 to offset P2, or set t = 0.5 to offset the point in the middle of P1 and P2. You can also pick any other t including below 0 and above 1 for extrapolation.

Use a positive offset to move the new point to the right side of the line and a negative offset to move it to the left side.

1 Like