title: Javascript spring physics: Apply direction vector to spring
body: <p>I'm implementing spring physics in Javascript, inspired by <a href="http://ghoscher.me/2013/03/02/simple-spring-physics/" rel="nofollow noreferrer">this blog post</a>. My system uses Hooke's Law formula to calculate spring forces:</p>
  
  <pre><code>F = -k(|x|-d)(x/|x|) - bv
  </code></pre>
  
  <p>I made <a href="http://codepen.io/andrewray/pen/epGyob?editors=001" rel="nofollow noreferrer">a CodePen</a> that shows the implementation of a spring between two points. The CodePen has two points connected by a spring, and every 2 seconds the point positions are randomized. You can see the points bounce on the spring towards each other.</p>
  
  <p>If you look at the source, you can see I've defined a direction vector for my spring:</p>
  
  <pre><code>var spring = {
      length: 100,
      direction: {
          x: 1, y: 1
      }
  };
  </code></pre>
  
  <p><strong>I'm trying to make it so that the spring always "resolves" in this direction.</strong> Put another way, I'd like the spring to always be "pointing" up and to the right. If this were implemented in the CodePen, it means the resting orientation of the points would <strong>always be the green point on the bottom left, and the blue point on the top right</strong>. No matter where the points start, they should end up in the following orientation (which matches the direction vector):</p>
  
  <p><a href="https://i.stack.imgur.com/oK2Lp.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oK2Lp.jpg" alt="Spring Hell"></a></p>
  
  <p>I've tried multiplying the normals by the spring vector:</p>
  
  <pre><code>norm1 = multiplyVectors( normalize( sub1 ), spring.direction ),
  </code></pre>
  
  <p>However this is a noop because the vector is <code>(1,1)</code>. I've been hacking on this system for a few days now and I'm stuck. How can I constrain my 2d spring to a specific direction?</p>