Created
December 27, 2022 15:01
-
-
Save eqs/451a7b2ce44cd8a02b1fea22496721dd to your computer and use it in GitHub Desktop.
Turtle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
classdef Turtle < handle | |
% MATLABで簡易のTurtle Graphicsを行うためのクラス | |
% | |
% Turtle Properties: | |
% p - Turtleの位置を表す行ベクトル [x, y] | |
% penOnPaper - trueならTurtleの軌跡を描画する | |
% | |
% Turtle Methods: | |
% moveTo - Turtleを位置 pDst に移動させる | |
% penUp - Turtleが移動した軌跡を描画しない | |
% penDown - Turtleが移動した軌跡を描画する | |
properties | |
p | |
penOnPaper | |
end | |
properties (Access=private) | |
fig | |
marker | |
end | |
methods | |
function obj = Turtle() | |
obj.fig = figure; | |
xlim([-10.0, 10.0]); | |
ylim([-10.0, 10.0]); | |
pbaspect([1, 1, 1]); | |
obj.p = [0.0, 0.0]; | |
obj.penOnPaper = true; | |
hold on; | |
obj.marker = plot(obj.p(1), obj.p(2), 'ro'); | |
hold off; | |
end | |
function moveTo(obj, pDst) | |
figure(obj.fig); | |
pSrc = obj.p; | |
pDist = sqrt(sum((pSrc - pDst) .^2)); | |
pDist = max(3, int32(pDist)); | |
t = linspace(0.0, 1.0, pDist); | |
for k = 1:length(t)-1 | |
s = (1.0 - t(k)) * pSrc + t(k) * pDst; | |
e = (1.0 - t(k+1)) * pSrc + t(k+1) * pDst; | |
segm = [s; e]; | |
hold on; | |
if obj.penOnPaper | |
l = line(segm(:, 1), segm(:, 2)); | |
l.Color = 'black'; | |
l.LineWidth = 1; | |
end | |
obj.marker.XData = e(1); | |
obj.marker.YData = e(2); | |
hold off; | |
drawnow(); | |
pause(1.0 / 100.0); | |
end | |
obj.p = pDst; | |
end | |
function penUp(obj) | |
obj.penOnPaper = false; | |
end | |
function penDown(obj) | |
obj.penOnPaper = true; | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment