我正在尝试在matlab中制作用户交互动画。它是一个可以在屏幕上转换和旋转的正方形,用户必须点击它。如果他们点击它,他们将获得积分,动画将重复。如果他们点击空格(例如:动画将退出并显示"YOU LOSE"。我已经用两个函数完成了动画。一个用于创建动画,另一个用于注册鼠标点击。到目前为止,我可以识别鼠标点击和动画将停止,如果用户单击空白,但动画不会重复,如果用户在多边形内单击。我不确定如何修改我的代码,使动画将重复,直到用户单击空白。我把我的代码粘贴在下面。如有任何帮助,我将不胜感激。
动画功能: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
编辑:修正了回调函数中的一些错误
简短回答
在while循环中包含动画
长回答
无论用户做什么,动画都只会播放一次,因为它不知道要重复。这个问题的答案是使用while循环,它会重复你的动画,直到你告诉它停止。主循环变成
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