Using pygame create a fabric simulation, didn't use any other modules, fabric created…
- User
Using pygame create a fabric simulation, didn't use any other modules, fabric created from simple grid, provide full code
- Assistant
Sure! Below is a full Pygame script that simulates a simple fabric using a grid of particles connected by constraints. This simulation uses only Pygame and no other external modules. The fabric reacts to gravity, and you can interact with it using the mouse.
Overview
- Particles: Each point in the grid is a particle with position, previous position (for Verlet integration), acceleration, and whether it's pinned or movable.
- Constraints: Particles are connected to their neighbors (structural constraints) to maintain the fabric's integrity.
- Physics: The simulation uses Verlet integration for movement, applying gravity and resolving constraints to simulate realistic fabric behavior.
- Interaction: Click and drag particles to interact with the fabric.
Full Code
import pygame import sys import math # Initialize Pygame pygame.init() # Screen dimensions WIDTH, HEIGHT = 800, 600 SCREEN = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Fabric Simulation") # Clock for controlling frame rate CLOCK = pygame.time.Clock() FPS = 60 # Colors BACKGROUND = (50, 50, 50) PARTICLE_COLOR = (200, 200, 200) PIN_COLOR = (255, 0, 0) CONSTRAINT_COLOR = (100, 100, 100) # Simulation parameters GRAVITY = pygame.math.Vector2(0, 0.5) DAMPING = 0.99 CONSTRAINT_ITERATIONS = 5 PARTICLE_RADIUS = 4 class Particle: def __init__(self, x, y, pinned=False): self.pos = pygame.math.Vector2(x, y) self.prev_pos = pygame.math.Vector2(x, y) self.acceleration = pygame.math.Vector2(0, 0) self.pinned = pinned def apply_force(self, force): self.acceleration += force def update(self): if self.pinned: return velocity = (self.pos - self.prev_pos) * DAMPING self.prev_pos = self.pos.copy() self.pos += velocity self.pos += self.acceleration self.acceleration = pygame.math.Vector2(0, 0) def draw(self, surface): color = PIN_COLOR if self.pinned else PARTICLE_COLOR pygame.draw.circle(surface, color, (int(self.pos.x), int(self.pos.y)), PARTICLE_RADIUS) class Constraint: def __init__(self, p1, p2, rest_length=None): self.p1 = p1 self.p2 = p2 if rest_length is None: self.rest_length = self.current_length() else: self.rest_length = rest_length def current_length(self): return (self.p1.pos - self.p2.pos).length() def resolve(self): delta = self.p2.pos - self.p1.pos delta_length = delta.length() if delta_length == 0: delta_length = 0.0001 difference = (delta_length - self.rest_length) / delta_length if not self.p1.pinned and not self.p2.pinned: self.p1.pos += delta * 0.5 * difference self.p2.pos -= delta * 0.5 * difference elif self.p1.pinned: self.p2.pos -= delta * difference elif self.p2.pinned: self.p1.pos += delta * difference def draw(self, surface): pygame.draw.line(surface, CONSTRAINT_COLOR, (int(self.p1.pos.x), int(self.p1.pos.y)), (int(self.p2.pos.x), int(self.p2.pos.y)), 1) def create_fabric(start_x, start_y, rows, cols, spacing, pinned_rows=1): particles = [] constraints = [] # Create particles for y in range(rows): for x in range(cols): pos_x = start_x + x * spacing pos_y = start_y + y * spacing pinned = y < pinned_rows # Pin the top rows particle = Particle(pos_x, pos_y, pinned) particles.append(particle) # Create constraints (structural) for y in range(rows): for x in range(cols): idx = y * cols + x if x < cols - 1: constraints.append(Constraint(particles[idx], particles[idx + 1])) if y < rows - 1: constraints.append(Constraint(particles[idx], particles[idx + cols])) # Shear constraints (optional for more realism) if x < cols - 1 and y < rows - 1: constraints.append(Constraint(particles[idx], particles[idx + cols + 1])) if x > 0 and y < rows - 1: constraints.append(Constraint(particles[idx], particles[idx + cols - 1])) return particles, constraints def main(): # Create fabric start_x = 200 start_y = 50 rows = 20 cols = 30 spacing = 20 particles, constraints = create_fabric(start_x, start_y, rows, cols, spacing, pinned_rows=2) selected_particle = None offset = pygame.math.Vector2(0, 0) running = True while running: CLOCK.tick(FPS) SCREEN.fill(BACKGROUND) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = pygame.math.Vector2(event.pos) for p in particles: if (p.pos - mouse_pos).length() < PARTICLE_RADIUS + 2: selected_particle = p offset = p.pos - mouse_pos break elif event.type == pygame.MOUSEBUTTONUP: selected_particle = None # Apply gravity for p in particles: p.apply_force(GRAVITY) # Update particles for p in particles: p.update() # Drag the selected particle if selected_particle: mouse_pos = pygame.math.Vector2(pygame.mouse.get_pos()) selected_particle.pos = mouse_pos + offset selected_particle.prev_pos = selected_particle.pos.copy() # Resolve constraints for _ in range(CONSTRAINT_ITERATIONS): for c in constraints: c.resolve() # Draw constraints for c in constraints: c.draw(SCREEN) # Draw particles for p in particles: p.draw(SCREEN) pygame.display.flip() pygame.quit() sys.exit() if __name__ == "__main__": main()Explanation
-
Particle Class:
- Represents each point in the fabric.
- Uses Verlet integration for smooth physics.
- Can be pinned (fixed in space) or movable.
-
Constraint Class:
- Connects two particles to maintain a certain distance (
rest_length). - Resolves the positions of connected particles to enforce the constraint.
- Connects two particles to maintain a certain distance (
-
create_fabric Function:
- Initializes a grid of particles.
- Creates constraints between neighboring particles (structural and shear constraints for better fabric behavior).
-
Main Loop:
- Handles events (mouse interactions to drag particles).
- Applies gravity to all particles.
- Updates particle positions using Verlet integration.
- Resolves constraints multiple times per frame for stability.
- Renders constraints and particles.
-
Interaction:
- Click near a particle to select and drag it.
- Pinned particles (top rows) stay fixed, anchoring the fabric.
Running the Simulation
-
Ensure Pygame is Installed:
pip install pygame -
Save the Script:
- Save the provided code in a file named, for example,
fabric_simulation.py.
- Save the provided code in a file named, for example,
-
Run the Script:
python fabric_simulation.py
Customization
-
Fabric Size:
- Adjust
rows,cols, andspacingin thecreate_fabricfunction to change the fabric's size and resolution.
- Adjust
-
Pinned Rows:
- Change
pinned_rowsto pin more or fewer rows at the top.
- Change
-
Physics Parameters:
- Modify
GRAVITY,DAMPING, andCONSTRAINT_ITERATIONSto tweak the simulation's behavior.
- Modify
-
Adding Wind or Other Forces:
- You can extend the
apply_forcemethod to include additional forces like wind.
- You can extend the
This script provides a foundational fabric simulation. You can enhance it by adding features like tearing, different constraint types, collision detection with other objects, or more sophisticated rendering.