I am constructing a rectangle based on a point with a parameter of length and width. and I want am trying to rotate this rectangle based on the calculated direction vector
[d1 d2] = [(x_old - X_cur) (Y_old - YCur)]
Code:
% Point coordinates current positon (small dark circle)
P = [2; 2];
% Direction vector
d = [1 1];
% Dimensions of rectangle
l = 20;
w = 10;
% %direction angle:
A = (atan2(d(1), d(2)));
% Original corner points of rectangle (straight rectangle)
x1 = P(1) -w/2;
y1 = P(2)+l;
x2 = P(1)+ w/2;
y2 = P(2)+l;
x3 = P(1)+ w/2;
y3 = P(2);
x4 = P(1) -w/2;
y4 = P(2);
rect = [x1 x2 x3 x4; y1 y2 y3 y4];
%rotated rectangles coordinates:
x1_new = P(1)+ ((x1 - P(1))* cos(A)) - (y1 - P(2))*sin(A);
y1_new = P(2) +(x1-P(1))*sin(A) + (y1-P(2))*cos(A);
x2_new = P(1)+ (x2 - P(1))* cos(A) - (y2 - P(2))*sin(A);
y2_new = P(2) +(x2-P(1))*sin(A) + (y2-P(2))*cos(A);
x3_new = P(1)+ (x3 - P(1))* cos(A) - (y3 - P(2))*sin(A);
y3_new = P(2) +(x3-P(1))*sin(A) + (y3-P(2))*cos(A);
x4_new = P(1)+ (x4 - P(1))* cos(A) - (y4 - P(2))*sin(A);
y4_new = P(2) +(x4-P(1))*sin(A) + (y4-P(2))*cos(A);
new_rect = [x1_new x2_new x3_new x4_new; y1_new y2_new y3_new y4_new];
%
%plot:
figure(1);
plot(P(1), P(2), 'k.', 'MarkerSize', 41);
hold on;
plot([P(1) P(1)+d(1)*10], [P(2) P(2)+d(2)*10], 'b'); %plot the direction
patch(new_rect(1,:),new_rect(2,:), 'b', 'FaceAlpha', 0.2); %plot rotated rectangle
patch(rect(1,:),rect(2,:),'b') %plot straight rectangle
hold off
I know there is some mistake in rotating the rectangle because its rotating on the other side. I tried all the possible combinations while creating the new coordinates.
any suggestions on where I am going wrong would be helpful
You can use a rotation matrix. The rotation will be applied to each coordinate at once:
% Rectangle coordinate
% x y
R = [2, 3
5, 3
5, 8
2, 8]
%Anonymous function that will create the rotation matrix (input in radian)
romat = @(a)[cos(a), -sin(a); sin(a), cos(a)];
%Rotation of the Rectangle, with A = atan2(d(1), d(2));
Rrot = ((R-mean(R))*romat(A))+mean(R)
During the operation we have to substract the center of mass of the rectangle so the rotation will occur around the [0,0] point.
Results:
hold on
%Rectangle
patch(R(:,1),R(:,2),'green')
%Rotated rectangle
patch(Rrot(:,1),Rrot(:,2),'red','facealpha',0.5)
%Euclidian vector
quiver(mean(R(:,1)),mean(R(:,2)),d(1),d(2),...
'ro','MarkerFaceColor','red','linewidth',3)
axis equal
What's wrong with your code:
You apply the following rotation matrix:
M = [cos(a) sin(a)
-sin(a) cos(a)]
instead of
M = [cos(a) -sin(a)
sin(a) cos(a)]