基于方向向量旋转矩形

Rotating a rectangle based on the direction vector

我正在构造一个基于具有长度和宽度参数的点的矩形。我想尝试根据计算出的方向向量旋转这个矩形

[d1 d2] = [(x_old - X_cur) (Y_old - YCur)]

代码:

% 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

我知道旋转矩形有一些错误,因为它在另一边旋转。我在创建新坐标时尝试了所有可能的组合。

任何关于我哪里出错的建议都会有所帮助

您可以使用旋转矩阵。旋转将立即应用于每个坐标:

%    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)

在操作过程中,我们必须减去矩形的质心,因此旋转将围绕 [0,0] 点进行。

结果:

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

你的代码有什么问题:

您应用以下旋转矩阵:

M = [cos(a) sin(a)
    -sin(a) cos(a)]

而不是

M = [cos(a) -sin(a)
     sin(a)  cos(a)]