我正在尝试在matlab中创建用户交互式动画。它是一个在屏幕上进行平移和旋转的正方形,用户必须单击它。如果他们点击它,他们将收到积分,动画将重复。如果他们点击空格(例如,除了广场内的任何地方)动画将退出并显示你丢失。我的动画几乎完成了使用两个功能。一个用于创建动画,另一个用于注册鼠标单击。到目前为止,我可以识别鼠标单击,如果用户点击空白,动画将停止,但如果用户在多边形内单击,动画将不会重复。我不确定如何修改我的代码,以便动画将重复,直到用户单击空白区域。我在下面粘贴了我的代码。任何帮助将不胜感激。
动画功能:
function movingPolygon
global gUserHitPolygon;
global gCurrentXVertices;
global gCurrentYVertices;
gUserHitPolygon = true;
nSides =4;
%Polar points
r=1;
theta = pi/nSides * (1:2:2*nSides-1);
%Cartesisn points
x0 = r * cos(theta);
y0 = r * sin(theta);
nFrames = 100;
xx = linspace(0,10, nFrames);
yy = xx;
rr = linspace(0, 2*pi, nFrames);
h = figure;
set(h,'WindowButtonDownFcn', @mouseDownCallback);
for i = 1:nFrames
rX = [cos(rr(i)), -sin(rr(i))];
rY = [sin(rr(i)), cos(rr(i))];
x1 = rX * [x0; y0];
y1 = rY * [x0; y0];
x2= x1 + xx(i);
y2= y1 + yy(i);
gCurrentXVertices=x2;
gCurrentYVertices=y2;
y=fill(x2, y2, 'b');
xlim([0,10]); ylim([0,10]);
hold on;
pause(0.000000003);
if ~gUserHitPolygon
clear GLOBAL gUserHitPolygon gCurrentXVertices gCurrentYVertices;
break;
end
delete(y);
end
end
回调功能:
function mouseDownCallback(~,~)
global UserHitPolygon;
global CurrentXVertices;
global CurrentYVertices;
xVertices = gCurrentXVertices;
yVertices = gCurrentYVertices;
% if we have valid (so non-empty) sets of x- and y-vertices then...
if ~isempty(xVertices) && ~isempty(yVertices)
% get the coordinate on the current axis
coordinates = get(gca,'CurrentPoint');
coordinates = coordinates(1,1:2);
% if the coordinate is not in the polygon, then change the
% flag
if ~inpolygon(coordinates(1),coordinates(2),xVertices,yVertices)
gUserHitPolygon = false;
end
end
end
编辑:修复了回调函数中的一些错误。
答案 0 :(得分:0)
在while循环中包含动画
无论用户做什么,动画只会播放一次,因为它不知道重复。答案是使用while loop,它将重复你的动画,直到你告诉它停止。然后你的主循环变为
done = false; % your stopping condition
while ~done
for i = 1:nFrames
rX = [cos(rr(i)), -sin(rr(i))];
rY = [sin(rr(i)), cos(rr(i))];
x1 = rX * [x0; y0];
y1 = rY * [x0; y0];
x2= x1 + xx(i);
y2= y1 + yy(i);
gCurrentXVertices=x2;
gCurrentYVertices=y2;
y=fill(x2, y2, 'b');
xlim([0,10]); ylim([0,10]);
hold on;
pause(0.000000003);
if ~gUserHitPolygon
clear GLOBAL gUserHitPolygon gCurrentXVertices gCurrentYVertices;
done = true; % set your stopping condition
break;
end
delete(y);
end
end