% Animated trajectories with moving red dots following ODE dynamics
clear; close all; clc;

% Domain
xrange = linspace(-1.5,1.5,60);
yrange = linspace(-1.5,1.5,60);
[X,Y] = meshgrid(xrange, yrange);

% Potential function
Pot = X.^4/4 - X.^2/2 + X.^2.*Y.^2;

% Plot potential contours
figure('units', 'normalized', 'outerposition', [0,0,1,1]);
clin=linspace(-1,2,100);
contourf(X, Y, Pot, clin,'LineWidth',1);
colormap parula
colorbar; hold on;
xlabel('x'); ylabel('y');
title('Trajectories with moving points (true ODE motion)');
axis equal;
xlim([min(xrange) max(xrange)]);
ylim([min(yrange) max(yrange)]);
set(gca,'FontSize',12,'Box','on');

% ODE system
odefun = @(t,z) [ -z(1).^3 + z(1) - 2*(z(2).^2).*z(1);
                  -2*(z(1).^2).*z(2) ];

% Boundary initial conditions
N = 50;
b = linspace(-1.5,1.5,N);
initconds = [ b' repmat(-1.5,N,1);
              b' repmat( 1.5,N,1);
              repmat(-1.5,N,1) b';
              repmat( 1.5,N,1) b' ];

% Time span and common animation time vector
tspan = [0 20];
t_anim = linspace(tspan(1), tspan(2), 600);  % uniform time points

% Store solutions
num_traj = size(initconds,1);
Xsol = zeros(num_traj, length(t_anim));
Ysol = zeros(num_traj, length(t_anim));

for k = 1:num_traj
    [t,z] = ode45(odefun, tspan, initconds(k,:));
    Xsol(k,:) = interp1(t, z(:,1), t_anim, 'linear');
    Ysol(k,:) = interp1(t, z(:,2), t_anim, 'linear');
end

% Create plotted trajectories (lines) and moving dots
trajLines = gobjects(num_traj,1);
dots = gobjects(num_traj,1);

for k = 1:num_traj
    trajLines(k) = plot(nan, nan, 'LineWidth', 1.4); % path drawn over time
    dots(k) = plot(Xsol(k,1), Ysol(k,1), 'ro', ...
        'MarkerFaceColor','r','MarkerSize',6);       % moving point
end

%Animation loop
pause
for j = 1:length(t_anim)
    for k = 1:num_traj
        set(trajLines(k), 'XData', Xsol(k,1:j), 'YData', Ysol(k,1:j));
        set(dots(k), 'XData', Xsol(k,j), 'YData', Ysol(k,j));
    end
    drawnow;      % ensures each frame actually renders
    pause(0.01);  % <-- slows the animation (increase to go slower)
end