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

Hi there,

Please, help me to resolve this quite simple task:

I’d like to write a script to set a position of P3 node at right angle to the line defined by P1 and P2 points. With some offset of course.

def movePoint(x1, y1, x2, y2, offset):
  # please, someone write this code :)
  return position

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


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.

I love you! :heart::heart:

1 Like