сделай софт бади физику на p5js
- User
сделай софт бади физику на p5js
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
сделай софт бади физику на p5js
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, let's create a simple 2D soft body simulation using p5.js. We'll model the soft body as a collection of point masses (particles) connected by springs.
Core Concepts:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
<style>
body { margin: 0; overflow: hidden; background-color: #222; }
canvas { display: block; }
</style>
<title>p5.js Soft Body Physics</title>
</head>
<body>
<script>
// --- Simulation Parameters ---
const gravity = 0.5; // Strength of gravity
const damping = 0.98; // Energy loss factor (prevents infinite oscillation)
const springStiffness = 0.05; // How stiff the springs are
const particleRadius = 8; // Visual size of particles
const numParticles = 20; // Number of particles forming the circle
const bodyRadius = 100; // Initial radius of the soft body circle
const tearSensitivity = 5; // How much stretch before a spring breaks (higher = less likely)
// --- Global Variables ---
let particles = [];
let springs = [];
let draggedParticle = null;
let mouseOffset = null;
// --- Particle Class ---
class Particle {
constructor(x, y) {
this.pos = createVector(x, y);
this.vel = createVector(0, 0);
this.acc = createVector(0, 0);
this.mass = 1; // Keep it simple for now
this.radius = particleRadius;
this.color = color(random(100, 255), random(100, 255), random(100, 255), 200);
}
applyForce(force) {
// F = ma => a = F/m
let f = p5.Vector.div(force, this.mass);
this.acc.add(f);
}
update() {
// Apply gravity
this.applyForce(createVector(0, gravity * this.mass));
// Verlet integration could be more stable, but let's use simple Euler for now
this.vel.add(this.acc);
this.vel.mult(damping); // Apply damping
this.pos.add(this.vel);
// Reset acceleration for the next frame
this.acc.mult(0);
}
checkEdges() {
// Bounce off edges
if (this.pos.x < this.radius) {
this.pos.x = this.radius;
this.vel.x *= -0.8; // Lose some energy on bounce
} else if (this.pos.x > width - this.radius) {
this.pos.x = width - this.radius;
this.vel.x *= -0.8;
}
if (this.pos.y < this.radius) {
this.pos.y = this.radius;
this.vel.y *= -0.8;
} else if (this.pos.y > height - this.radius) {
this.pos.y = height - this.radius;
this.vel.y *= -0.8;
// Prevent sinking slightly below floor due to gravity step
if (abs(this.vel.y) < 1) this.vel.y = 0;
}
}
display() {
noStroke();
fill(this.color);
ellipse(this.pos.x, this.pos.y, this.radius * 2);
}
}
// --- Spring Class ---
class Spring {
constructor(p1, p2, stiffness) {
this.p1 = p1; // Reference to the first particle
this.p2 = p2; // Reference to the second particle
this.k = stiffness; // Spring constant
// Calculate rest length based on initial distance
this.restLength = p5.Vector.dist(this.p1.pos, this.p2.pos);
this.broken = false;
}
applyForce() {
if (this.broken) return;
// Vector pointing from p1 to p2
let force = p5.Vector.sub(this.p2.pos, this.p1.pos);
let currentLength = force.mag();
// Check if spring should break
if (abs(currentLength - this.restLength) > this.restLength * tearSensitivity) {
this.broken = true;
return; // Stop applying force if broken
}
// Calculate displacement from rest length
let displacement = currentLength - this.restLength;
// Calculate force magnitude (Hooke's Law: F = -k * x)
// The negative sign is handled by the direction of the force vector
let forceMagnitude = this.k * displacement;
// Normalize the force vector (get direction) and multiply by magnitude
force.normalize();
force.mult(forceMagnitude);
// Apply the force to both particles (equal and opposite)
this.p1.applyForce(force);
force.mult(-1); // Invert force for the other particle
this.p2.applyForce(force);
}
display() {
if (this.broken) return; // Don't draw broken springs
// Draw a line representing the spring
// Color based on stretch/compression
let d = p5.Vector.dist(this.p1.pos, this.p2.pos);
let diff = d - this.restLength;
let maxStretch = this.restLength * 0.5; // Arbitrary max visualization stretch
// Map difference to color (blue = compressed, white = rest, red = stretched)
let r = map(constrain(diff, 0, maxStretch), 0, maxStretch, 255, 255);
let g = map(constrain(diff, -maxStretch, maxStretch), -maxStretch, maxStretch, 0, 255);
let b = map(constrain(diff, -maxStretch, 0), -maxStretch, 0, 255, 255);
stroke(r, g, b, 150); // Semi-transparent
strokeWeight(map(abs(diff), 0, maxStretch, 1, 3, true)); // Thicker when stressed
line(this.p1.pos.x, this.p1.pos.y, this.p2.pos.x, this.p2.pos.y);
}
}
// --- p5.js Setup Function ---
function setup() {
createCanvas(windowWidth, windowHeight);
// Create particles in a circle
let centerX = width / 2;
let centerY = height / 3;
for (let i = 0; i < numParticles; i++) {
let angle = map(i, 0, numParticles, 0, TWO_PI);
let x = centerX + cos(angle) * bodyRadius;
let y = centerY + sin(angle) * bodyRadius;
particles.push(new Particle(x, y));
}
// Create springs connecting adjacent particles (outer ring)
for (let i = 0; i < numParticles; i++) {
let p1 = particles[i];
let p2 = particles[(i + 1) % numParticles]; // Wrap around for the last spring
springs.push(new Spring(p1, p2, springStiffness));
}
// Create internal "structural" springs (optional, adds stability)
let internalStiffness = springStiffness * 0.5; // Make internal springs less stiff
for (let i = 0; i < numParticles; i++) {
for (let j = i + 2; j < numParticles; j++) {
// Connect particles that are not immediate neighbors
let distance = min(j - i, numParticles - (j - i)); // Check shorter path around circle
if (distance > 1 && distance < numParticles / 3) { // Connect somewhat nearby points
springs.push(new Spring(particles[i], particles[j], internalStiffness));
}
}
}
}
// --- p5.js Draw Loop ---
function draw() {
background(51); // Dark background
// --- Update Physics ---
// Apply spring forces
for (let spring of springs) {
spring.applyForce();
}
// Handle mouse dragging
if (draggedParticle) {
draggedParticle.pos.set(mouseX + mouseOffset.x, mouseY + mouseOffset.y);
draggedParticle.vel.set(0, 0); // Stop movement while dragging
}
// Update particles (forces, velocity, position, constraints)
for (let particle of particles) {
// Don't update physics for the dragged particle (it's controlled by mouse)
if (particle !== draggedParticle) {
particle.update();
particle.checkEdges();
}
}
// --- Drawing ---
// Draw springs first (behind particles)
for (let spring of springs) {
spring.display();
}
// Draw filled shape (optional, looks more "solid")
fill(150, 150, 250, 80); // Semi-transparent fill
noStroke();
beginShape();
for (let particle of particles) {
curveVertex(particle.pos.x, particle.pos.y); // Use curveVertex for smoother shape
}
// Add first two and last two points again for curveVertex continuity
if (particles.length > 2){
curveVertex(particles[0].pos.x, particles[0].pos.y);
curveVertex(particles[1].pos.x, particles[1].pos.y);
}
endShape(CLOSE);
// Draw particles on top
for (let particle of particles) {
particle.display();
}
// Draw drag indicator (optional)
if (draggedParticle) {
stroke(255, 0, 0);
strokeWeight(2);
noFill();
ellipse(draggedParticle.pos.x, draggedParticle.pos.y, draggedParticle.radius * 3);
}
}
// --- Mouse Interaction ---
function mousePressed() {
let closestDist = Infinity;
let candidate = null;
// Find the particle closest to the mouse click
for (let particle of particles) {
let d = dist(mouseX, mouseY, particle.pos.x, particle.pos.y);
if (d < particle.radius * 2 && d < closestDist) { // Click within ~2x radius
closestDist = d;
candidate = particle;
}
}
if (candidate) {
draggedParticle = candidate;
// Calculate offset from particle center to mouse click position
mouseOffset = p5.Vector.sub(draggedParticle.pos, createVector(mouseX, mouseY));
// Temporarily make it heavier/less affected by springs while dragging (optional)
// draggedParticle.mass *= 5;
draggedParticle.vel.set(0,0); // Stop its current motion
}
}
function mouseDragged() {
// Position update happens in draw() loop if draggedParticle is set
}
function mouseReleased() {
if (draggedParticle) {
// Restore original mass if changed
// draggedParticle.mass /= 5;
draggedParticle = null;
mouseOffset = null;
}
}
// --- Window Resize Handling ---
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
// Could potentially reposition particles if needed, but usually not necessary
}
</script>
</body>
</html>
How to Run:
softbody.html).Explanation:
Particle Class: Manages individual points, their movement, and forces acting on them. update() applies physics, checkEdges() handles boundary collisions.Spring Class: Connects two Particle instances. applyForce() calculates the force based on Hooke's Law and the current distance vs. restLength. It also includes a basic tearSensitivity to break springs under high stress. display() draws the spring, changing color based on stretch/compression.setup(): Creates the canvas, initializes particles in a circular arrangement, and creates springs connecting adjacent particles and some internal ones for stability.draw(): The main animation loop:
curveVertex for a smoother look (optional).mousePressed finds the nearest particle to click and "grabs" it. mouseDragged lets the draw loop handle positioning. mouseReleased drops the particle.windowResized: Adjusts the canvas size if the browser window changes.Things to Try:
gravity, damping, springStiffness, numParticles, bodyRadius, tearSensitivity. See how the behavior changes.