сделай софт бади физику на 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.
Ниже приведён пример простой симуляции мягкого тела (soft body) на p5.js. В этом примере мы создаём сетку из точек (частиц), соединённых "пружинами" (связями), которая ведёт себя как эластичная ткань или желе. Вы можете экспериментировать с параметрами для изменения поведения.
Чтобы опробовать код, скопируйте его в HTML-файл и откройте в браузере.
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<title>Soft Body Physics на p5.js</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
<style>
body {
margin: 0;
overflow: hidden;
background: #222;
}
</style>
</head>
<body>
<script>
// Параметры симуляции
const GRAVITY = 0.5;
const FRICTION = 0.99;
const SPRING_STIFFNESS = 0.2;
const SPRING_DAMPING = 0.9;
const POINT_RADIUS = 4;
// Сетка мягкого тела
const GRID_COLS = 10;
const GRID_ROWS = 10;
const GRID_SPACING = 20;
// Массивы для точек и пружин (связей)
let points = [];
let springs = [];
// Для перетаскивания точек
let draggedPoint = null;
// Класс для частиц (точек)
class Point {
constructor(x, y, locked = false) {
this.x = x;
this.y = y;
this.px = x; // предыдущая позиция (для verlet-интеграции)
this.py = y;
this.locked = locked; // если true, точка не подвержена физике
}
update() {
if (this.locked) return;
// Используем verlet-интеграцию
let vx = (this.x - this.px) * FRICTION;
let vy = (this.y - this.py) * FRICTION;
// Запоминаем текущую позицию
this.px = this.x;
this.py = this.y;
// Применяем гравитацию и обновляем позицию
this.x += vx;
this.y += vy + GRAVITY;
}
// Рисуем точку
draw() {
fill(255);
noStroke();
ellipse(this.x, this.y, POINT_RADIUS * 2);
}
}
// Класс для связи (пружины) между двумя точками
class Spring {
constructor(p1, p2, restLength) {
this.p1 = p1;
this.p2 = p2;
this.restLength = restLength;
}
update() {
let dx = this.p2.x - this.p1.x;
let dy = this.p2.y - this.p1.y;
let distance = sqrt(dx * dx + dy * dy);
let difference = this.restLength - distance;
let percent = (difference / distance) * SPRING_STIFFNESS;
let offsetX = dx * percent;
let offsetY = dy * percent;
if (!this.p1.locked) {
this.p1.x -= offsetX;
this.p1.y -= offsetY;
}
if (!this.p2.locked) {
this.p2.x += offsetX;
this.p2.y += offsetY;
}
}
draw() {
stroke(200);
line(this.p1.x, this.p1.y, this.p2.x, this.p2.y);
}
}
function setup() {
createCanvas(windowWidth, windowHeight);
// Создаем сетку точек
points = [];
springs = [];
// Центрируем мягкое тело в окне
let startX = width / 2 - (GRID_COLS - 1) * GRID_SPACING / 2;
let startY = height / 4;
for (let j = 0; j < GRID_ROWS; j++) {
for (let i = 0; i < GRID_COLS; i++) {
// Закрепляем верхнюю строку (фиксированные)
let locked = (j === 0);
let p = new Point(startX + i * GRID_SPACING, startY + j * GRID_SPACING, locked);
points.push(p);
}
}
// Создаем пружины (связи) между соседними точками
for (let j = 0; j < GRID_ROWS; j++) {
for (let i = 0; i < GRID_COLS; i++) {
let index = j * GRID_COLS + i;
// Горизонтальная связь
if (i < GRID_COLS - 1) {
springs.push(new Spring(points[index], points[index + 1], GRID_SPACING));
}
// Вертикальная связь
if (j < GRID_ROWS - 1) {
springs.push(new Spring(points[index], points[index + GRID_COLS], GRID_SPACING));
}
// Диагональные связи для жесткости
if (i < GRID_COLS - 1 && j < GRID_ROWS - 1) {
let diagLength = sqrt(GRID_SPACING * GRID_SPACING * 2);
springs.push(new Spring(points[index], points[index + GRID_COLS + 1], diagLength));
}
if (i > 0 && j < GRID_ROWS - 1) {
let diagLength = sqrt(GRID_SPACING * GRID_SPACING * 2);
springs.push(new Spring(points[index], points[index + GRID_COLS - 1], diagLength));
}
}
}
}
function draw() {
background(51);
// Обновляем точки (верт-логика)
for (let p of points) {
p.update();
}
// Несколько раз прогоняем связи для устойчивости симуляции
for (let k = 0; k < 5; k++) {
for (let s of springs) {
s.update();
}
}
// Рисуем связи
for (let s of springs) {
s.draw();
}
// Рисуем точки
for (let p of points) {
p.draw();
}
}
// Перетаскивание точек мышью
function mousePressed() {
for (let p of points) {
let d = dist(mouseX, mouseY, p.x, p.y);
if (d < POINT_RADIUS * 2) {
draggedPoint = p;
break;
}
}
}
function mouseDragged() {
if (draggedPoint && !draggedPoint.locked) {
draggedPoint.x = mouseX;
draggedPoint.y = mouseY;
}
}
function mouseReleased() {
draggedPoint = null;
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
}
</script>
</body>
</html>
Структура:
Симуляция:
locked), чтобы обеспечить подвешенный вид ткани или желе.Интерактивность:
Этот пример – отправная точка. Вы можете расширять его, добавляя, например, столкновения с препятствиями, другие силы или даже управляемые деформации, чтобы создать более сложную и интересную симуляцию мягкого тела на p5.js.