Last active
December 17, 2015 08:29
-
-
Save mikolalysenko/5580867 to your computer and use it in GitHub Desktop.
Spring!
This file contains hidden or 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
//Config variables | |
var rest_length = 256.0 | |
var spring_constant = 1.0 | |
var dt = 0.01 | |
//Hooke's law | |
function force(displacement) { | |
return spring_constant * (rest_length - displacement) | |
} | |
//State of system | |
var x = 0.0 | |
var v = 0.0 | |
//Integrate forward by dt | |
function step() { | |
var f = force(x) | |
x += (v + f * 0.5 * dt) * dt | |
v += (f + force(x)) * 0.5 * dt | |
} | |
//Set up canvas | |
var canvas = document.createElement("canvas") | |
canvas.width = 512 | |
canvas.height = 512 | |
document.body.appendChild(canvas) | |
var context = canvas.getContext("2d") | |
//Animate! | |
setInterval(function() { | |
context.clearRect(0, 0, 512, 512) | |
context.fillStyle = "rgba(0,0,0,255)" | |
context.beginPath() | |
context.arc(x, 256, 10, 0, Math.PI*2, true); | |
context.closePath(); | |
context.fill() | |
step() | |
}, 10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment