# EXERCÍCIO 3 - Animação independente da órbita da Terra usando método de Euler

import sympy as sy
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

# Constantes
G = 4 * np.pi**2  # AU^3 / (M * ano^2)
M_sol = 1.0       # Massa do Sol em unidades astronômicas
dt = 0.001        # Passo de tempo em anos
t_max = 1.0       # Tempo total de simulação (1 ano)
n_steps = int(t_max / dt)

# Condições iniciais
r = np.array([1.0, 0.0])             # posição inicial (AU)
v = np.array([0.0, 2 * np.pi])       # velocidade inicial (AU/ano)

# Armazenamento da trajetória
x_vals = [r[0]]
y_vals = [r[1]]

# Método de Euler
for _ in range(n_steps):
    r_mag = np.linalg.norm(r)
    F_grav = -G * M_sol * r / r_mag**3
    v += F_grav * dt
    r += v * dt
    x_vals.append(r[0])
    y_vals.append(r[1])

# Criar figura para animação
fig, ax = plt.subplots(figsize=(6, 6))
ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
ax.set_xlabel('x (AU)')
ax.set_ylabel('y (AU)')
ax.set_title('Animação da Órbita da Terra (Euler)')
ax.grid(True)

# Sol na origem
ax.plot(0, 0, 'yo', label='Sol')
terra, = ax.plot([], [], 'bo', label='Terra')
traco, = ax.plot([], [], 'b--', linewidth=0.5)

# Atualização da animação
def update(frame):
    terra.set_data([x_vals[frame]], [y_vals[frame]])  
    traco.set_data(x_vals[:frame], y_vals[:frame])
    return terra, traco


# Criar animação
ani = FuncAnimation(fig=fig, func=update, frames=len(x_vals), interval=10, blit=True)
plt.legend()
plt.show()
