Running ginput while also running a loop in MATLAB

2019-09-17 11:42发布

问题:

I want to display a crosshair in one of the games I'm making in MATLAB. I tried using the ginput because it would be perfect as it displays crosshairs and reads in the x and y locations of what was clicked. However, since it always waits for a click and I have moving objects, it causes the object to be created on the screen and then not move. How do I get the loop to run and continue moving the object while ginput is also running and evaluating clicks?

回答1:

Very similar to Update figure while waiting for event in Matlab?

To summarize: ginput is not good for real time interactive functions and really more of an annotation tool. Look at the ButtonDownFcn property of the figure. The link also includes a small example of how you would implement something like this. I will copy here for clarity but original credit goes to pm89 and grantnz

% Stop button
uicontrol(...
    'Style','pushbutton', 'String', 'Stop',...
    'Units','Normalized', 'Position', [0.4 0.1 0.2 0.1],...
    'Callback', 'run = 0;');

% Axes
ax = axes(...
    'Units','Normalized',...
    'OuterPosition', [0 0.2 1 0.8]);

run = 1;
t = 0;
while run
    t = t + 0.01; x = t:0.01:t+2;
    h = plot(ax, x, sin(x));
    set(ax, 'ButtonDownFcn', 'get(ax, ''CurrentPoint'')');
    xlim([x(1) x(end)]); ylim([-1 1]);
    pause(0.01);
end


标签: matlab ginput