Вращение прямоугольника на основе вектора направления - PullRequest
1 голос
/ 05 июня 2019

Я строю прямоугольник на основе точки с параметром длины и ширины. и я хочу, чтобы повернуть этот прямоугольник на основе рассчитанного вектора направления

[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

Я знаю, что есть некоторая ошибка при вращении прямоугольника, потому что он вращается с другой стороны. Я перепробовал все возможные комбинации при создании новых координат.

enter image description here

любые предложения о том, где я иду не так, будут полезны

1 Ответ

2 голосов
/ 05 июня 2019

Вы можете использовать матрицу вращения.Вращение будет применено к каждой координате сразу:

%    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

enter image description here

Что не так с вашим кодом:

Вы применяете следующую матрицу вращения:

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

вместо

M = [cos(a) -sin(a)
     sin(a)  cos(a)]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...