Instantly share code, notes, and snippets.

Embed
What would you like to do?
Coding Challenge #102: 2D Water Ripple
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/p5.min.js"></script>
<script>
// Coding Challenge #102: 2D Water Ripple -
// Video: https://www.youtube.com/watch?v=BZUdGqeOD0w
// Algorithm: https://web.archive.org/web/20160418004149/http://freespace.virgin.net/hugo.elias/graphics/x_water.htm
let cols, rows,
current = [],
previous = [],
damping = 0.9;
function mouseDragged() {
current[mouseX][mouseY] = 255
}
function setup() {
pixelDensity(1)
createCanvas(200, 200)
cols = width
rows = height
for (let i = 0; i < cols; i++) {
current[i] = []
previous[i] = []
for (let j = 0; j < rows; j++) {
current[i][j] = 0
previous[i][j] = 0
}
}
previous[100][100] = 255
}
function draw() {
background(0)
loadPixels()
for (let i = 1; i < cols - 1; i++) {
for (let j = 1; j < rows - 1; j++) {
current[i][j] =
(previous[i - 1][j] + previous[i + 1][j] +
previous[i][j - 1] + previous[i][j + 1] +
previous[i - 1][j - 1] + previous[i - 1][j + 1] +
previous[i + 1][j - 1] + previous[i + 1][j + 1]
) / 4 - current[i][j];
current[i][j] = current[i][j] * damping
let index = (i + j * cols) * 4;
pixels[index + 0] = current[i][j] * 255
pixels[index + 1] = current[i][j] * 255
pixels[index + 2] = current[i][j] * 255
pixels[index + 3] = 255
}
}
updatePixels()
//swap buffers
let temp = previous
previous = current
current = temp
}
</script>
@tlindow

This comment has been minimized.

tlindow commented May 25, 2018

If you include the following within the mouseDragged function, it should be able to work:

  let x = floor(mouseX)
  let y = floor(mouseY)
  current[x][y] = 255;

Hope this helps!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment