calculating perpendicular point

Hello everyone,

I am trying to do this mathematically in Unity. Assuming there is a line between two points A and B. There is a third point C, outside this line. I want to deduce the point D in the line AB that when a line is drawn from C to that point D, it will make that new line CD perpendicular to the line AB.

Therefore: A, B, C are already known, and I want to calculate the position of D within the AB line. For the sake of simplicity the four points can be seen as Vector2. Outlining the required equation to calculate the point D will be enough for me.

Thank you.

I just solved this problem myself. I doubt laying down the solution for this might be useful to someone in the future, but I know it wont hurt, so here it is

A = (x1,y1), B = (x2,y2), C = (x3, y3), D = (x4, y4)
x1, y1, x2, y2, x3, y3 are known, in order to calculate x4 and y4 we do the following

k = ((y2-y1) * (x3-x1) - (x2-x1) * (y3-y1)) / ((y2-y1)^2 + (x2-x1)^2)
x4 = x3 - k * (y2-y1)
y4 = y3 + k * (x2-x1)

Hello,
Thanks for the post. That was exactly what I was looking for.

Vector3 normAB = AB.normalized;
float magAD = Vector3.dot(normAB, AC);

Vector3 D = A + normAB * magAD

Not sure if this existed when this thread was created, but Unity has a built-in function that can do this (vector projection) in a single step.

Vector3 D = Vector3.Project(C, Vector3.Normalize(B - A));

EDIT:
On further investigation I found this doesn’t work. I’m still pretty sure this function can be used to do the same thing but I appear to be using it wrong. I’ve implemented alexzzzz’s method and it works great.