Of course! Building on the math concepts we just covered, let's create a fun, interactive demo.
We will build a "jiggly blob" made of several points connected by springs. One central point will be an "anchor" that follows the mouse, and the other points will jiggle around it, trying to maintain their shape.
The Plan
JigglePoint Class: A point with mass, position, velocity, and acceleration. It will know how to update itself based on forces (Euler integration).
Spring Class: Connects two JigglePoints. It will calculate the spring force (Hooke's Law) and apply it to the connected points.
- Main Program:
- Set up a Pygame window.
- Create a central
anchor_point that will be fixed to the mouse position.
- Create several
jiggle_points in a circle around the anchor.
- Create
springs to connect:
- Each
jiggle_point to the anchor_point.
- Each
jiggle_point to its neighbors in the circle (to maintain the blob's shape).
- In the game loop, we'll update the springs (to apply forces) and then update the points (to move them).
Here is the complete, commented code. Copy and paste it into a Python file (e.g., jiggle_demo.py) and run it.
import pygame
import math
from pygame.math import Vector2
# --- Constants ---
SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600
FPS = 60
BACKGROUND_COLOR = (20, 30, 40)
POINT_COLOR = (200, 220, 255)
ANCHOR_COLOR = (255, 100, 100)
SPRING_COLOR = (100, 120, 140)
# --- Physics Parameters ---
# Feel free to tweak these to see how they affect the simulation!
NUM_POINTS = 12 # Number of points in the outer circle of the blob
BLOB_RADIUS = 100 # The resting radius of the blob
DAMPING = 0.98 # Energy loss factor (0.0 to 1.0)
POINT_MASS = 1.0 # Mass of each jiggle point
# Spring stiffness (k value in Hooke's Law)
# Higher value = stiffer spring
STIFFNESS_OUTER = 1.5 # Stiffness of springs connecting outer points
STIFFNESS_INNER = 1.0 # Stiffness of springs connecting to the center anchor
# --- Classes ---
class JigglePoint:
"""Represents a point mass in our physics simulation."""
def __init__(self, x, y, mass=POINT_MASS):
self.pos = Vector2(x, y)
self.vel = Vector2(0, 0)
self.acc = Vector2(0, 0)
self.mass = mass
# Anchor points don't move based on physics
self.is_anchor = False
def add_force(self, force):
"""Accumulates forces acting on the point."""
# Newton's 2nd Law: F = ma => a = F/m
self.acc += force / self.mass
def update(self, dt):
"""Updates position and velocity using Euler integration."""
if self.is_anchor:
# Anchors are controlled externally (e.g., by the mouse)
self.vel = Vector2(0, 0)
self.acc = Vector2(0, 0)
return
# Standard Euler integration
self.vel += self.acc * dt
self.pos += self.vel * dt
# Apply damping to lose energy and stabilize
self.vel *= DAMPING
# Reset acceleration for the next frame's force calculation
self.acc = Vector2(0, 0)
def draw(self, screen):
"""Draws the point on the screen."""
color = ANCHOR_COLOR if self.is_anchor else POINT_COLOR
pygame.draw.circle(screen, color, (int(self.pos.x), int(self.pos.y)), 5)
class Spring:
"""Represents a spring connecting two JigglePoints."""
def __init__(self, point_a, point_b, stiffness):
self.point_a = point_a
self.point_b = point_b
self.stiffness = stiffness
# Calculate the resting length from the initial positions
self.rest_length = self.point_a.pos.distance_to(self.point_b.pos)
def update(self):
"""Calculates and applies spring forces (Hooke's Law)."""
# Vector pointing from A to B
vec_ab = self.point_b.pos - self.point_a.pos
current_length = vec_ab.length()
# Avoid division by zero if points are at the same spot
if current_length == 0:
return
# The displacement from the spring's resting length
# A positive value means the spring is stretched
# A negative value means the spring is compressed
displacement = current_length - self.rest_length
# Force = -k * x (where x is the displacement vector)
# Here, we calculate magnitude and direction separately for clarity
force_magnitude = self.stiffness * displacement
# The direction of the force is along the spring (normalized vector)
direction = vec_ab.normalize()
force = force_magnitude * direction
# Apply the forces to the points (Newton's 3rd Law: equal and opposite)
if not self.point_a.is_anchor:
self.point_a.add_force(force)
if not self.point_b.is_anchor:
self.point_b.add_force(-force) # Opposite direction for point B
def draw(self, screen):
"""Draws a line representing the spring."""
pygame.draw.line(screen, SPRING_COLOR, self.point_a.pos, self.point_b.pos, 2)
# --- Main Setup ---
def main():
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Jiggle Physics Demo")
clock = pygame.time.Clock()
# --- Create the Jiggle Body ---
points = []
springs = []
# 1. Create the central anchor point
center_x, center_y = SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2
anchor_point = JigglePoint(center_x, center_y)
anchor_point.is_anchor = True
points.append(anchor_point)
# 2. Create the outer jiggle points in a circle
for i in range(NUM_POINTS):
angle = (i / NUM_POINTS) * 2 * math.pi # Angle in radians
x = center_x + BLOB_RADIUS * math.cos(angle)
y = center_y + BLOB_RADIUS * math.sin(angle)
point = JigglePoint(x, y)
points.append(point)
# 3. Create springs connecting outer points to the anchor
springs.append(Spring(anchor_point, point, STIFFNESS_INNER))
# 4. Create springs connecting outer points to their neighbors
if i > 0:
# Connect to the previous point
prev_point = points[-2]
springs.append(Spring(point, prev_point, STIFFNESS_OUTER))
# Connect the last outer point back to the first outer point
springs.append(Spring(points[-1], points[1], STIFFNESS_OUTER))
# --- Game Loop ---
running = True
while running:
# Time-based physics update
dt = clock.tick(FPS) / 1000.0
# Prevent huge dt values if the window is dragged
dt = min(dt, 1/30.0)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# --- Update Step ---
# 1. Update the anchor to the mouse position
anchor_point.pos.update(pygame.mouse.get_pos())
# 2. Update all springs to calculate and apply forces
for spring in springs:
spring.update()
# 3. Update all points to integrate forces and move
for point in points:
point.update(dt)
# --- Draw Step ---
screen.fill(BACKGROUND_COLOR)
for spring in springs:
spring.draw(screen)
for point in points:
point.draw(screen)
pygame.display.flip()
pygame.quit()
if __name__ == "__main__":
main()
How to Run and Play
- Make sure you have Pygame installed (
pip install pygame).
- Save the code above as a Python file (e.g.,
jiggle_demo.py).
- Run it from your terminal:
python jiggle_demo.py.
- A window will appear. Move your mouse around the screen to see the jiggle body follow and deform!
Key Math Concepts in Action
- Vectors (
pygame.math.Vector2): Used everywhere for position, velocity, acceleration, and forces. This makes all the math (addition, subtraction, normalization, finding distance) clean and easy.
- Hooke's Law (in
Spring.update):
displacement = current_length - self.rest_length calculates the scalar displacement (x).
force_magnitude = self.stiffness * displacement calculates the force magnitude (F = kx).
force = force_magnitude * direction turns it into a proper force vector by giving it the correct direction.
- Numerical Integration (in
JigglePoint.update):
self.vel += self.acc * dt is the Euler integration step for velocity.
self.pos += self.vel * dt is the Euler integration step for position.
- Damping (in
JigglePoint.update):
self.vel *= DAMPING is our simple velocity damping. It slowly bleeds energy out of the system, preventing the blob from jiggling forever and making it look more natural.
Have fun experimenting by changing the constants at the top of the file