Плоская манипуляция Используя мышь пробела MATLAB® Object

В этом примере показано, как использовать Мышь Пробела через интерфейс MATLAB®.

После запуска этого примера виртуальная сцена с самолетом отображена в Средстве просмотра Simulink® 3D Animation™. Можно переместиться по плоскости в сцене с помощью Мыши Пробела. Путем нажатия кнопки 1 устройства можно поместить маркер в текущем плоском положении.

Этот пример требует Мыши Пробела или другого совместимого устройства.

Создайте и инициализируйте объект мыши пробела

ID устройства установлен в USB1 в примере. Если ваше устройство использует различную связь, установите ID соответственно. Допустимые значения для ID мыши пробела:

COM1, COM2, COM3, COM4, USB1, USB2, USB3, or USB4.

ПРИМЕЧАНИЕ: предупреждающее сообщение распечатано, если Мышь Пробела не соединяется.

ID = 'USB1';
MOUSE = [];
try
  % try to create the space mouse object
  MOUSE = vrspacemouse(ID);
catch ME
  fprintf('Unable to initialize the Space Mouse on port %s.\n', ID);
end
Unable to initialize the Space Mouse on port USB1.

Загрузите и просмотрите виртуальный мир

% create and open the vrworld object
w = vrworld('vrtkoff_hud.wrl', 'new');
open(w);

% create the vrfigure showing the virtual scene
% use a viewpoint suitable for user navigation
fig = vrfigure(w, 'Viewpoint', 'Ride on the Plane');

% get the manipulated airplane node
airpln = vrnode(w, 'Plane');
% read plane initial translation and rotation
originalTranslation = airpln.translation;
originalRotation = airpln.rotation;

% set the HUD display text
offset = vrnode(w, 'HUDOffset');
offset.translation = offset.translation + [-0.15 1.9 0];
hudtext = vrnode(w, 'HUDText1');
hudstr = { 'Press button ''1'' to drop a marker', ...
           'Press button ''2'' to reset plane position', ...
           'Press buttons ''1'' and ''2'' to exit' };
hudtext.string = hudstr;
vrdrawnow;

Добавьте EXTERNPROTO для маркеров траектории

Загрузите форму четырехгранника PROTO из файла VRML, содержащего различные формы маркера.

% get the path to the wrl file with marker PROTOs
pathtomarkers = which('vr_markers.wrl');
% use the tetrahedron shape
MarkerName = 'Marker_Tetrahedron';
% create an EXTERNPROTO with specified marker
try
  addexternproto(w, pathtomarkers, MarkerName);
catch ME
  % if required PROTO is already contained don't throw an exception
  if ~strcmpi(ME.identifier, 'sl3d:interface:protoexists')
    throwAsCaller(ME);
  end
end

Навигация в сцене

Интерактивная навигация закончена или путем нажатия Space Mouse buttons 1 и 2 одновременно или путем закрытия фигуры Средства просмотра Simulink 3D Animation.

if ~isempty(MOUSE)

  % iterator that ensures unique DEF names for created markers
  iterforname = 0;

  % set the mouse sensitivity for translations
  % higher values correspond to higher sensitivity
  MOUSE.PositionSensitivity = 1e-2;
  % set the mouse sensitivity for rotations
  % higher values correspond to higher sensitivity
  MOUSE.RotationSensitivity = 1e-5;

  % read the space mouse values and update the scene objects in a cycle
  % repeat unless buttons '1' and '2' simultaneously pressed or figure closed
  while any(button(MOUSE, [1 2]) == 0) && isvalid(fig)
     pause(0.01);
     % use the method vrspacemouse/viewpoint to get the current translation and rotation
     V = viewpoint(MOUSE);
     % set the new translation to the aircraft node
     airpln.translation = originalTranslation + [-1 1 -1].*V(1:3);
     % set the new rotation to the aircraft node
     airpln.rotation = [-1 1 -1 1].*V(4:7);
     if button(MOUSE, 1) == 1
       % if mouse button '1' pressed create a new marker
       newMarker = vrnode(w, sprintf('%s_%d', 'Marker', iterforname), MarkerName);
       % set marker translation
       newMarker.markerTranslation = originalTranslation + [-1 1 -1].*V(1:3);
       % increment the iterator
       iterforname = iterforname + 1;
     end
     if button(MOUSE, 2) == 1
       % if mouse button '2' pressed reset the plane position and rotation
       airpln.translation = originalTranslation;
       airpln.rotation = originalRotation;
       MOUSE.InitialPosition = [0 0 0];
       MOUSE.InitialRotation = [0 0 0];
     end
     % redraw the virtual scene
     vrdrawnow;
  end
end

Очистка

% close the vrfigure
close(fig);
% close the vrworld
close(w);
% clear all used variables
clear ID MOUSE w fig airpln originalTranslation originalRotation offset hudtext hudstr ...
      pathtomarkers MarkerName iterforname V newMarker img_capture img;

% display the end of example message
Для просмотра документации необходимо авторизоваться на сайте