参考代码:
function dog_chase_rabbit
Vt = 3; % 野兔速度
V = 5; % 猎狗速度
X0 = [70; 15; 0; -60]; % 初始位置
psi2 = -atan2(X0(4), X0(3)); % 野兔逃跑方向
opt = odeset('reltol',1e-6,'abstol',1e-7,'Events',@events);
[t,X] = ode45(@chase, [0 100], X0,opt);
% 绘图
clf
hold on
plot(0,0,'go')
text(0,0,'Hole ','Horiz','right','Vert','bottom','color','g')
plot(X0(1),X0(2),'r^')
text(X0(1),X0(2),' Dog','Horiz','left','color','r')
plot(X0(3),X0(4),'b^')
text(X0(3),X0(4),' Hare','Horiz','left','Vert','top','color','b')
plot(X(:,1),X(:,2),'r-',X(:,3),X(:,4),'b--')
plot(X(end,1),X(end,2),'rx')
ylim([-60 20])
axis equal off
plot(xlim,[0 0],':',[0 0],ylim,':','color',[1 1 1]*.7)
% 微分方程
function dX = chase(t, X)
% X(1,2) - x1 y1
x1 = X(1); y1 = X(2);
x2 = X(3); y2 = X(4);
Q = atan2(y2-y1, x2-x1);
dX = [ ...
V * cos(Q); V * sin(Q); ...
Vt * cos(psi2); Vt * sin(psi2) ...
];
end
% 设置结束事件
function [value,isterminal,direction] = events(t,X)
% 距离小于0.001时结束仿真
value = sqrt((X(3)-X(1))^2+(X(4)-X(2))^2) - 1e-3;
isterminal = 1;
direction = -1;
end
end
结果如图,红色是猎狗轨迹,蓝色是野兔轨迹,猎狗可在“x”处抓住野兔。