Verlet integrator, to deal with an argument from the pub.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

#### 73 lines 1.9KB Raw Permalink Blame History

 ``````""" Implements Verlet integration """ import pygame import numpy as np SIZE = (800, 800) CENTER = np.array(SIZE) / 2 WHITE = (255, 255, 255) DAMPING = 0.99 class Ball(object): def __init__(self, x, y, radius=5, mass=1, fixed=False): self.pos = np.array([x, y]) self.last_pos = np.array([x, y]) self.velocity = np.array([0., 0.]) self.radius = radius self.mass = mass self.fixed = fixed def render(self, screen): x, y = self.pos + CENTER pygame.draw.circle(screen, WHITE, [int(x), int(y)], self.radius, 4) def update(self): if self.fixed: return # Gravity #self.pos[1] += .05 # Bounce if self.pos[1] > 400: self.pos[1] = 400 self.last_pos[1] = 400 self.velocity[1] = -.5 * self.velocity[1] self.pos += self.velocity self.velocity = self.pos - self.last_pos self.velocity *= DAMPING self.last_pos = np.array(self.pos) class Spring(object): def __init__(self, a, b, length=None, k=0.3, color=WHITE): self.a = a self.b = b self.k = k self.length = self.compute_length() if length is None else length self.color = color print(self.length) def render(self, screen): x1, y1 = self.a.pos + CENTER x2, y2 = self.b.pos + CENTER pygame.draw.line(screen, self.color, [x1, y1], [x2, y2]) def compute_length(self): x1, y1 = self.a.pos + CENTER x2, y2 = self.b.pos + CENTER return np.sqrt((x2 - x1)**2 + (y2 - y1)**2) def update(self): current_length = self.compute_length() delta = self.b.pos - self.a.pos delta /= current_length stretch = (current_length - self.length) / self.length self.a.velocity += stretch * delta * self.k self.b.velocity -= stretch * delta * self.k``````