-
-
Save ds604/228483d2498cdfdf79ef9df22676b899 to your computer and use it in GitHub Desktop.
Coding Challenge #102: 2D Water Ripple
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you include the following within the mouseDragged function, it should be able to work:
Hope this helps!