Search code examples
pythonvectortrigonometryvertices

moving arrowhead across its body


I have created the following function which gets two line points and outputs three points of an arrowhead triangle. What I need to add is a length according to which the arrowhead will be poisitioned away from the point B across the line AB. To explain it better, I would like it like this: A----->--B where the two dashes are equal to the length

def create_arrowhead(A, B):
    """
    Calculate the arrowheads vertex positions according to the edge direction.

    Parameters
    ----------
    A : array
    x,y Starting point of edge
    B : array
    x,y Ending point of edge

    Returns
    -------
    B, v1, v2 : tuple
    The point of head, the v1 xy and v2 xy points of the two base vertices of the arrowhead.
    """
    w = 0.005 # half width of the triangle base
    h = w * 0.8660254037844386467637  # sqrt(3)/2

    mag = math.sqrt((B[0] - A[0])**2.0 + (B[1] - A[1])**2.0)

    u0 = (B[0] - A[0]) / (mag)
    u1 = (B[1] - A[1]) / (mag)
    U = [u0, u1]
    V = [-U[1], U[0]]
    v1 = [B[0] - h * U[0] + w * V[0], B[1] - h * U[1] + w * V[1]]
    v2 = [B[0] - h * U[0] - w * V[0], B[1] - h * U[1] - w * V[1]]

    return (B, v1, v2)

Solution

  • I finally found the solution. By multiplying a variable of distance with the unit vector's components and subtracting this result from B's coordinates. This will create a point on the line AB with distance d from B.

    def create_arrowhead(A, B, d):
    """
    Use trigonometry to calculate the arrowheads vertex positions according to the line direction.
    
    Parameters
    ----------
    A : array
        x,y Starting point of line segment
    B : array
        x,y Ending point of line segment
    
    Returns
    -------
    C, v1, v2 : tuple
        The point of head with distance d from point B, the v1 xy and v2 xy points of the two base vertices of the arrowhead.
    """
    w = 0.003 # Half of the triangle base width
    h = w / 0.26794919243 # tan(15)
    
    AB = [B[0] - A[0], B[1] - A[1]]
    mag = math.sqrt(AB[0]**2.0 + AB[1]**2.0)
    
    u0 = AB[0] / mag
    u1 = AB[1] / mag
    U = [u0, u1] # Unit vector of AB
    
    V = [-U[1], U[0]] # Unit vector perpendicular to AB
    
    C = [ B[0] - d * u0, B[1] - d * u1 ]
    
    v1 = [C[0] - h * U[0] + w * V[0], C[1] - h * U[1] + w * V[1]]
    v2 = [C[0] - h * U[0] - w * V[0], C[1] - h * U[1] - w * V[1]]
    
    return (C, v1, v2)