code a single p5.js script that simulates water
- User
code a single p5.js script that simulates water
- Assistant
Simulating water in p5.js can be achieved through various techniques, each offering unique visual effects. Below is an example of a water ripple simulation using a two-dimensional wave algorithm:
let cols, rows; let current; let previous; let dampening = 0.99; function setup() { createCanvas(400, 400); cols = width; rows = height; current = new Array(cols).fill().map(() => new Array(rows).fill(0)); previous = new Array(cols).fill().map(() => new Array(rows).fill(0)); } function draw() { background(0); loadPixels(); for (let x = 1; x < cols - 1; x++) { for (let y = 1; y < rows - 1; y++) { current[x][y] = (previous[x - 1][y] + previous[x + 1][y] + previous[x][y - 1] + previous[x][y + 1]) / 2 - current[x][y]; current[x][y] *= dampening; let index = (x + y * width) * 4; let color = map(current[x][y], -1, 1, 0, 255); pixels[index] = color; pixels[index + 1] = color; pixels[index + 2] = color; pixels[index + 3] = 255; } } updatePixels(); let temp = previous; previous = current; current = temp; } function mousePressed() { previous[mouseX][mouseY] = 500; }In this script, two matrices (
currentandprevious) represent the water surface. Thedrawfunction updates these matrices to simulate wave propagation, and clicking the mouse introduces disturbances, creating ripple effects. This approach is inspired by the water ripple effect discussed by Andrea Rastelli[1].For more complex simulations, such as fluid dynamics, you might explore the work of cqlim, who developed a fluid simulation using p5.js[2].
Additionally, the p5.js example "Soft Body" demonstrates simulating the physics of a soft body accelerating toward the mouse, which can be adapted for water-like effects[3].
These resources provide a solid foundation for creating water simulations in p5.js.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.