Find the Coordinates of a Unkown Point of a Triangle

80 Views Asked by At

The situation is as follows: I am creating a game in this game I have a line($A$ to $B$) and a mouse position $C$. Now I want to calculate point $D$ on line $A$$B$.

I know the coordinates of: $A$, $B$ and $C$ and the angle of point $B$. It should be possible to calculate point $D$ but I have no clue where to start. Can any one point me in a direction?

Note: it is possible that point $A$ and $B$ are on the same axis. For example: $A(1,1)$ and $B(1,3)$. Image

3

There are 3 best solutions below

0
On

I think you should drop the a line starting from $C$ over line $AB$ and calculate the angle between those two lines. You stop at the point where you get a $90 ^\circ$ angle. Now, there are various coding approximations and best fit algorithms you need to make i.e. how many iterations the loop should have and from where should you be starting. I think you should divide the line $AB$ in two and keep on dividing until you get the required point. That's the best solution I feel. I had to implement same condition as yours but I was using some API's. I hope this solution helps you out. Let me know if you find some other solution to this.

Thanks

2
On

Hint:

If $A=(x_A,y_A)$,$B=(x_B,y_B)$ and $C=(x_C,y_C)$ are knowns, than the line $AB$ has slope $m=\dfrac{y_B-y_A}{x_B-x_A}$ and the orthogonal line from $C$ has slope $m'=-\frac{1}{m}$. So the coordinates of the point $D$ are the solution of the system: $$ \begin{cases} y-y_C=-\frac{1}{m}(x-x_C)\\ y-y_A=m(x-x_A) \end{cases} $$

0
On

Do it with vectors!

Let A, B and C be position vectors of points A, B, C, so AB ( = A - B) is the vector from A to B, and DC (= D - C) is from D to C. Now AB and DC are perpendicular, so their dot product is zero. Let t be the ratio AD/AB (so it's 1 if D is at B, and 0 if it's at A).

These requirements give us: $$ D = A + tAB $$ $$ (D-C).AB = 0 $$ Solve for t: $$ (A + tAB - C).AB = 0 $$ $$ (A - C).AB - t(AB.AB) = 0 $$ $$ t = \frac{(A-C).AB}{AB.AB} = \frac{(A-C).AB}{\|AB\|^2}$$

Herewith some Python:

class Vector:
    def __init__(self, x, y):
        (self.x, self.y) = (x,y)

    def sub(self, other):
        return Vector( self.x - other.x, self.y - other.y )

    def add(self, other):
        return Vector( self.x - other.x, self.y - other.y )

    def dot(self, other):
        return self.x*other.x + self.y*other.y

    def scalarMul(self, s):
        return Vector( self.x * s, self.y * s )

def intersect(A,B,C):
    AB = A.sub(B)
    AC = A.sub(C)
    t = (AC.dot(AB)) / (AB.dot(AB))
    return A.add(AB.scalarMul(t))

A=Vector(4.5, 0.5)
B=Vector(0.5, 1.5)
C=Vector(1.5, 0.5)

D=intersect(A,B,C)
print D.x, D.y