2
votes

I have two rectangles with pivots,

I need to attach the position of the green rectangle based on the rotation of the red rectangle

The result should be like in the picture:

picture

I tried different formulas and nothing succeeded

red rectangle:

x=500, y=100, width=200, height=500, pivotX=100, pivotY=400

green rectangle:

x=450, y=150, width=100, height=400, pivotX=50, pivotY=50

I tried something like this:

var radians = (Math.PI / 180) * red.degree;
green.x += red.pivotX * Math.cos(radians) - red.pivotY * Math.sin(radians);
green.y += red.pivotX * Math.sin(radians) + red.pivotY * Math.cos(radians);

Big thanks to everyone that helped!

1
I think you also have to model the point on which the green rectangle is attached to the red rectangle. It is also unclear how the respective positions are related to the pivots.Codor

1 Answers

2
votes

The pivot of a rectangle is originally at position (x + pivotX, y + pivotY). Take the vector pointing from the red pivot point towards the green pivot point, namely

vx = green.x + green.pivotX - red.x - red.pivotX;
vy = green.y + green.pivotY - red.y - red.pivotY;

That's the vector you rotate:

wx = Math.cos(radians)*vx - Math.sin(radians)*vy;
wy = Math.sin(radians)*vx + Math.cos(radians)*vy;

Then you can use that rotated w instead of the original v to determine the position of the green rectangle:

green.x += wx - vx;
green.y += wy - vy;