Skip to content

Instantly share code, notes, and snippets.

@ryanmmmmm
Created July 3, 2014 16:38
Show Gist options
  • Save ryanmmmmm/80a222f221a4cbefb326 to your computer and use it in GitHub Desktop.
Save ryanmmmmm/80a222f221a4cbefb326 to your computer and use it in GitHub Desktop.
For Alex firstcollision
{"description":"For Alex firstcollision","endpoint":"","display":"svg","public":true,"require":[],"fileconfigs":{"inlet.js":{"default":true,"vim":false,"emacs":false,"fontSize":12},"_.md":{"default":true,"vim":false,"emacs":false,"fontSize":12},"config.json":{"default":true,"vim":false,"emacs":false,"fontSize":12}},"fullscreen":false,"play":false,"loop":false,"restart":false,"autoinit":true,"pause":true,"loop_type":"pingpong","bv":false,"nclones":15,"clone_opacity":0.4,"duration":3000,"ease":"linear","dt":0.01,"ajax-caching":true,"thumbnail":"http://i.imgur.com/OLeLXr9.png"}
function forced (gravity) {
var w = 1280,
h = 800;
var nodes = d3.range(200).map(function() { return {radius: Math.random() * 6.2 + 5}; }),
color = d3.scale
.linear()
.range(['#000', '#ff70c8'])
var force = d3.layout.force()
.gravity(gravity)
.charge(function(d, i) { return i ? 0 : -2000; })
.nodes(nodes)
.size([w, h]);
var root = nodes[0];
root.radius = 0;
root.fixed = true;
force.start();
var svg = d3.select("svg").append("svg:svg")
.attr("width", w)
.attr("height", h);
var a = svg.selectAll("circle")
.data(nodes.slice(1))
.enter().append("svg:circle")
.transition()
.duration(6873).attr('r',0)
.attr("r", function(d) { return d.radius - 2; })
.style("fill", function(d, i) { return color(i % 3); });
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; });
});
svg.on("mousemove", function() {
var p1 = d3.mouse(this);
root.px = p1[0];
root.py = p1[1];
force.resume();
});
svg.on("click", function() {
var p1 = d3.mouse(this);
// force.stop();
// root.radius = 100;
nodes.push(nodes[0]);
});
}
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;
};
}
forced(0.10);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment