Drag dots to see them get atracted back to the center.
forked from mbostock's block: Collision Detection
license: gpl-3.0 |
Drag dots to see them get atracted back to the center.
forked from mbostock's block: Collision Detection
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<body> | |
<script src="//d3js.org/d3.v3.min.js"></script> | |
<script> | |
var width = 960, | |
height = 500; | |
// 200 bolinhas (range) de mesmo tamanho (radius) | |
var nodes = d3.range(200).map(function() { return {radius: 8}; }), | |
root = nodes[0], // o centro é o primeiro nó | |
color = d3.scale.category10(); // escala com 10 cores (category10) | |
// https://github.com/d3/d3-3.x-api-reference/blob/master/Ordinal-Scales.md | |
root.radius = 0; | |
root.fixed = true; | |
var force = d3.layout.force() | |
.gravity(0.05) | |
.charge(function(d, i) { return 0; })// i ? 0 : -2000; }) | |
.nodes(nodes) | |
.size([width, height]); | |
force.start(); | |
var svg = d3.select("body").append("svg") | |
.attr("width", width) | |
.attr("height", height); | |
var node = svg.selectAll("circle") | |
.data(nodes.slice(1)) | |
.enter().append("circle") | |
.attr("r", function(d) { return d.radius; }) | |
// alterna três cores | |
// trocando a cor a cada resto de divisão por 3 (i%3) | |
.style("fill", function(d, i) { return color(i % 3); }) | |
.on("tick", tick) | |
.call(force.drag); | |
force.on("tick", function(e) { | |
var q = d3.geom.quadtree(nodes), | |
i = 0, | |
n = nodes.length; | |
while (++i < n) q.visit(collide(nodes[i])); | |
svg.selectAll("circle") | |
.attr("cx", function(d) { return d.x; }) | |
.attr("cy", function(d) { return d.y; }); | |
}); | |
// captura o movimento do mouse e | |
// atribui à posição do root | |
// a posição do cursor | |
svg.on("click", function() { | |
var p1 = d3.mouse(this); | |
root.px = p1[0]; | |
root.py = p1[1]; | |
force.resume(); | |
}); | |
function collide(node) { | |
var r = node.radius + 16, | |
nx1 = node.x - r, | |
nx2 = node.x + r, | |
ny1 = node.y - r, | |
ny2 = node.y + r; | |
return function(quad, x1, y1, x2, y2) { | |
if (quad.point && (quad.point !== node)) { | |
var x = node.x - quad.point.x, | |
y = node.y - quad.point.y, | |
l = Math.sqrt(x * x + y * y), | |
r = node.radius + quad.point.radius; | |
if (l < r) { | |
l = (l - r) / l * .5; | |
node.x -= x *= l; | |
node.y -= y *= l; | |
quad.point.x += x; | |
quad.point.y += y; | |
} | |
} | |
return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1; | |
}; | |
} | |
function tick() { | |
link.attr("x1", function(d) { return d.source.x; }) | |
.attr("y1", function(d) { return d.source.y; }) | |
.attr("x2", function(d) { return d.target.x; }) | |
.attr("y2", function(d) { return d.target.y; }); | |
node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); | |
} | |
</script> |