AttractionBehavior in conjunction with spring forces in toxiclibs

Has anyone solved these examples from Chapter 5 of Nature of Code? Example NOC_5_17: Use AttractionBehavior in conjunction with spring forces. From the chapter end exercise: In toxiclibs, use spring (or joint) connections between objects to control their interactions. Create and delete these springs on the fly.

Even if you haven't solved these, any tips would be helpful. I am looking to build a system where a system of circles are in random motion and come together to form linear chains. Using attraction/repulsion, they join into clusters. How do i restrict them to a linear conformation?

(The solutions for these aren't available at or the downloaded examples in Processing.


  • edited November 2017

    @sachinsrawat -- re:

    I am looking to build a system where a system of circles are in random motion and come together to form linear chains.

    Is this supposed to be modeling a specific process (if so what process?), or is this to create an aesthetic effect?

    When you say "clusters" what do you mean -- do nodes each have two connections?

    When you say "linear chains" do you mean any number of nodes (like 3 or more nodes) floating in a straight line, or do you mean each node exclusively having two connections (like links in a chain) and the last and first connections not being shared (no loop) -- but the chain can be wobbly?

    You may get more helpful feedback if you share your code.

  • edited November 2017

    @jeremydouglass - This is to see how colloids (sphere particles) that behave like active walkers polymerise into chains, so they would join into chains and break at certain probabilities. I’m stuck at how do I use attraction behaviour to make strictly chains, meaning each sphere particle shouldn’t be bound to not more than two other spheres.

  • edited November 2017

    Modeling polymerising in this way is pretty easy, because you have already defined the conditions, and they are easy to articulate as code rules: only bind if the number of bindings is less than 2.

    Without seeing your code example it is hard to know what your implementation might look like, but here is one sketch:

    class Colloid {
      int maxbind=2;
      float x, y;
      ArrayList<Colloid> bound = new ArrayList<Colloid>();  
      Colloid( ... ) { ... }
      boolean near (Colloid c){ ... }
      void bind(ArrayList<Colloid> neighbors){
        for (Colloid c : neighbors){
          if ( c.near(this) && bound.size()<2 ) {
          else {

    Note that this approach uses ArrayLists and a maxbind variable to be flexible -- so you could create a mix of Colloids that took 1, 2, or 3 bindings, for example. However this might not be relevant to your project.

Sign In or Register to comment.