Sure! Below is a complete Pygame demo where a soft "jiggly" circle follows the mouse cursor with spring-damper physics. The circle smoothly and naturally "jiggles" as it tries to catch up to the mouse position.
Features:
- The circle tries to follow the mouse position (which acts as the spring anchor).
- The circle has velocity and acceleration, so it jiggles with spring + damping forces.
- Adjustable stiffness and damping for different jiggle feels.
Code:
import pygame
from pygame.math import Vector2
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Mouse Following Jiggle Demo")
clock = pygame.time.Clock()
# Jiggle physics parameters
stiffness = 30.0 # Spring stiffness (higher = tighter spring)
damping = 8.0 # Damping coefficient (higher = less oscillation)
mass = 1.0 # Mass of the jiggle point
radius = 40 # Radius of the jiggle circle
# Initial state
position = Vector2(400, 300) # Start in center
velocity = Vector2(0, 0)
running = True
while running:
dt = clock.tick(60) / 1000 # Delta time in seconds (frame time)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Get mouse position as the spring anchor (rest position)
rest_position = Vector2(pygame.mouse.get_pos())
# Calculate spring force: F = -k * (x - x0)
spring_force = -stiffness * (position - rest_position)
# Calculate damping force: F = -d * v
damping_force = -damping * velocity
# Total force and acceleration
force = spring_force + damping_force
acceleration = force / mass
# Integrate velocity and position using Euler method
velocity += acceleration * dt
position += velocity * dt
# Drawing
screen.fill((30, 30, 30))
# Draw the anchor (mouse position)
pygame.draw.circle(screen, (0, 255, 0), rest_position, 8)
# Draw the jiggle circle
pygame.draw.circle(screen, (255, 100, 100), position, radius)
# Draw a line connecting anchor and jiggle point
pygame.draw.line(screen, (200, 200, 200), rest_position, position, 2)
pygame.display.flip()
pygame.quit()
How it works:
- The mouse position is the "rest position" or anchor point.
- The circle tries to move toward the mouse, but the spring force pulls it back if it moves too far.
- The damping force slows down the velocity to prevent infinite oscillations.
- The result is a smooth, natural jiggle effect as the circle follows the mouse.
Try tweaking these values for different effects:
stiffness = 50.0 # More stiffness = less stretch, faster snap
damping = 3.0 # Less damping = more oscillation, more jiggle
mass = 1.0 # Change mass to affect acceleration
If you want, I can help you extend this to multiple points or attach it to a sprite! Just ask.