Simon Meskens - 1 month ago 6x

Javascript Question

I have Cartesian coordinates P, P0 and P1, how do I find C?

Note that C is also the orthocenter of the triangle which has P as a vertex and P0 and P1 as altitudes.

This code will run a couple hundred times per second in a graphics renderer, in a program that is already doing complex physics, so it needs to be fast. I'm doing using it to calculate control points for quadratic curves. If possible, I'd like to avoid trig functions and calculating angles and stick to pure vector math.

Pure math answers are fine, even though I'm programming this in Javascript. Just keep in mind that the simpler the answer, the better, since any vector operation costs time.

Answer

Method 1:

Vectors CP0 and PP0 are perpendicular, and CP1 and PP1 are perpendicular, so we can write system of two equations for dot products of these vector pairs and find two unknown CX and CY (center coordinates)

```
CP0 = (CX - P0.X, CY - P0.Y)
CP1 = (CX - P1.X, CY - P1.Y)
PP0 = (P.X - P0.X, P.Y - P0.Y)
PP1 = (P.X - P1.X, P.Y - P1.Y)
Dot(CP0, PP0 ) = 0
Dot(CP1, PP1 ) = 0
(CX - P0.X) * (P.X - P0.X) + (CY - P0.Y) * (P.Y - P0.Y) = 0
(CX - P1.X) * (P.X - P1.X) + (CY - P1.Y) * (P.Y - P1.Y) = 0
```

Method 2:

Middle point M between P0 and P1 has coordinates

```
M.X = (P0.X + P1.X) / 2 ///1
M.Y = (P0.Y + P1.X) / 2 ///2
Distance P-M is DM
DM_Squared = (P.X-M.X)^2 + (P.Y-M.Y)^2 ///3
L, D distances are from your notation
L_Squared = (P.X-P0.X)^2 + (P.Y-P0.Y)^2 ///4
```

Theta is angle P0PC

```
Cos(Theta) = Length(P - M) / Length(P - P0) = DM / L
D = Length(C - P) = L / Cos(Theta) = L * L / DM
and finally
C = P - L^2 * (P0 - M) / DM^2
Coeff = L_Squared / DM_Squared ///5
C.X = P.X - Coeff * (P.X - M.X) ///6
C.Y = P.Y - Coeff * (P.Y - M.Y) ///7
```

Formulas 1..7 are ready-to-use

Source (Stackoverflow)

Comments