Hi Mallory,
The problem arises because each time the polygon's position changes, a new patch is created without removing the previous one.
We can update the position of the patch instead of creating a new patch each time:
function polygon
axis([0 100 0 100])
% Create the polygon
h = impoly(gca,[10 10 ; 20 10; 20 20 ; 10 20]);
api = iptgetapi(h);
current_body_coordinates = api.getPosition();
% Create a patch using the initial position
poly_patch = patch(current_body_coordinates(:,1), current_body_coordinates(:,2), 'r');
% Callback to update the patch
api.addNewPositionCallback(@update_patch);
% Function to update patch
function update_patch(p)
set(poly_patch, 'XData', p(:,1), 'YData', p(:,2));
end
end
For more information on 'patch' function, you can refer to - https://www.mathworks.com/help/matlab/ref/patch.html
Hope this helps.