N-body Toy

Skip to the toy!

D3.js provides a force-directed layout, which is nice for all sorts of data structures, especially those that contain complex relationships.

The charge is usually given a negative value, causing nodes to repel one another. Instead of calculating the force between each pair of nodes, the Barnes-Hut Algorithm gives an approximation that is less computationally intensive.

With three nodes and a positive charge, we have a simulation of the three body problem.

The force-directed layout defines gravity as the tendency for nodes to approach the center of the layout. By reducing the gravity and adding trails to the nodes, the emergent complexity becomes readily apparent.

We can measure the velocity each node traveled in an animation tick to gain some notion of a node's kinetic energy.

The measurement is drawn using the hue and lightness of the trail. These particles don't have collision detection.

Here is a toy for playing with the parameters of this layout. It builds off of Mike Bostock's graph constructor, which allows you to place links and nodes on the graph by clicking. Links are added when a node is placed while another node is within the cursor's reticle.

It is possible to create interesting configurations by balancing charge and gravity. Initially the charge and gravity are set to zero. And don't worry, if you lose your particles just increase the gravity until they reappear in the center.

Discuss on Hacker News