Built with blockbuilder.org
Last active
December 10, 2018 01:08
-
-
Save max-l/64544445b8921bba625e682eb02f9a08 to your computer and use it in GitHub Desktop.
balls bouncing in rectangle
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
license: mit |
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<style> | |
circle {fill: steelblue;} | |
svg {background: #f0fafe} | |
</style> | |
</head> | |
<body> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<script> | |
const width = 400 | |
const height = 200 | |
const radius = 10 | |
const stepDistance = 8 | |
var data = []; | |
var point_count = 20; | |
var svg = d3.select("body") | |
.append("svg") | |
.attr("width", width) | |
.attr("height", height) | |
.attr("color", "red") | |
const rnd = d3.randomUniform(1, 10) | |
d3.range(point_count).map(i=> { | |
data.push({ | |
id: i, x: 0, y: 0, | |
slope: rnd() / 10, | |
x_dir: 10,y_dir: 10, | |
}) | |
}) | |
redraw(data); | |
d3.interval(() => redraw(update(data)), 30) | |
function redraw(data){ | |
var circle = svg.selectAll("circle") | |
.data(data, d => d.id) | |
circle | |
.attr("r", radius) | |
.attr("cx", d => d.x) | |
.attr("cy", d => d.y) | |
circle.enter().append("circle") | |
.attr("r", radius) | |
//.attr("cx", 1)//d => d.x) | |
//.attr("cy", 1)//d => d.y) | |
} | |
const update = data => | |
data.map(d => calcPointB(d, stepDistance, d.slope)) | |
// given a point, p, and a distance, d, and a slope, m, return x and y | |
// formula from http://www.geeksforgeeks.org/find-points-at-a-given-distance-on-a-line-of-given-slope/ | |
const getDir = (coord, dir, dimension) => | |
Math.floor(coord) <= radius ? 1 : | |
Math.ceil(coord) >= dimension - radius ? -1 : dir; | |
const calcPointB = (p, d, m) => { | |
p.x_dir = getDir(p.x, p.x_dir, width); | |
p.y_dir = getDir(p.y, p.y_dir, height); | |
p.x = p.x + (d * Math.sqrt(1 / (1 + Math.pow(m, 2))) * p.x_dir); | |
p.y = p.y + (m * d * Math.sqrt(1 / (1 + Math.pow(m, 2))) * p.y_dir); | |
return p; | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment