mathrotationtransformtransformationvectormath

Calculate transform of object, to make it line up with another


Say I have two rectangles, each with a 'connector' that points in a certain direction. The transform (location and angle) of the link is specified relative to the centre of its parent rectangle.

In the example below, rectangle A's link is (x: 0, y: -0.5, rotation: 0) while B's is (x: 0.5, y: 0, rotation: 45).

Two rectangles can 'plug in' to eachother by rotating such that their links have the same coordinates and face opposite directions.

Diagram

I'm trying to figure out how to calculate the transform of rectangle B relative to rectangle A after they are linked.

In this case, rectangle A is (0, 0, 0), A's link is (0, 0.5, 0), B's link is (0, 0.5, 180) and B is (~0.3, ~-0.8, 135).

Does anyone know how to calculate B's final position in the above example?


Solution

  • So you have base points A0 and B0 and link points AL and BL

    At first you move B0 by difference of AL and BL, so

    B0' = B0 + AL - BL
    

    Then you have to rotate this point around AL to provide final position

    B0''.X = AL.X + (B0.X - BL.X) * Cos(D) - (B0.Y - BL.Y) * Sin(D)
    B0''.Y = AL.Y + (B0.X - BL.X) * Sin(D) + (B0.Y - BL.Y) * Cos(D)
    

    where D is angle of rotation

    D = Pi - A_rotation - B_rotation