Skip to content

Instantly share code, notes, and snippets.

@cmpolis
Created February 6, 2016 23:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmpolis/8d26ec5eb64fdd96d2d5 to your computer and use it in GitHub Desktop.
Save cmpolis/8d26ec5eb64fdd96d2d5 to your computer and use it in GitHub Desktop.
simple Newtonian physics sim
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
svg { width:100%; height: 100% }
</style>
</head>
<body>
<script>
var r = 8
var svg = d3.select("body").append("svg")
.append('g')
.attr('transform','translate(0,300)');
svg.append('line')
.attr('x1', 0)
.attr('x2', 1000)
.attr('y1', r)
.attr('y2', r)
.attr('stroke','black');
// "drop" balls from random heights
var xValues = d3.range(0,35).map(function(d) {
return {
y: Math.random() * 200,
v: 0};
});
//
var circleEnter = svg.selectAll('circle')
.data(xValues).enter()
.append('circle')
.attr('r', r)
.attr('cx', function(d, ndx) { return r + ndx * 30})
.attr('cy', function(d) { return -d.y; })
.attr('fill', 'steelblue')
.attr('fill-opacity', 1);
// update
var circleSel = svg.selectAll('circle');
setInterval(function() {
circleSel
.attr('cy', function(d) {
// gravity is '0.6' units, if floor is hit, dampen slightly
// and velocity changes signs, last ternary is for case
// to prevent ball from staying y < 0
d.v = d.y > 0 ? d.v-0.6 : (d.v < 0 ? -0.95*d.v : d.v-0.6);
d.y += d.v;
return -(d.y < 0 ? 0 : d.y); })
.attr('fill-opacity', function(d) { return Math.min(1, 0.2 + Math.abs(d.v/30)); });
}, 25);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment