0
\$\begingroup\$

enter image description here

Sorry for terrible picture but lets say we have a unit vector A and we have vectors B and C. So for vector B I would want to rotate in a positive direction because the vector is "above A" and for vector C i would want to rotate downwards. Is there an easy way of detecting which way to rotate?

\$\endgroup\$
  • 1
    \$\begingroup\$ The "positive" rotation is usually counter-clockwise, but that'd mean that both B and C would rotate counter-clockwise. Is your goal to have A "repel" both B and C ? \$\endgroup\$ – Quentin Sep 19 '16 at 10:01
0
\$\begingroup\$

The naïve approach would be to use the trig function arctan to calculate their current angles, then decide which way to rotate and at what speed to do so.

For example:

function rotateTowards(from, to, speed) {
  // τ is Tau, ~= 6.28318530718

  diff = to - from; // Find the angle delta
  if (diff < 0) diff += τ; // If the delta is out of the unit circle, wrap it back in.
  if (abs(diff) < speed) return to; // We're within speed of our target, return target.

  if (diff < 0) newAngle = from - speed;
  newAngle = from + speed;

  // Make sure our new angle is still valid.
  if (newAngle > τ) newAngle -= τ;
  if (newAngle < 0) newAngle += τ;

  return newAngle;
}

// Declare our vectors.
A = new Vector(-1, -0.5);
B = new Vector(-2, -3);
//C = new Vector(-1, -2.5); Not using C, but it's here for completeness.

// Calculate each vector's angle using atan2
angle_a = atan2(a.y, a.x);
angle_b = atan2(b.x, b.y);
//angle_c = atan2(c.x, c.y); Same as above.

// Calculate A's magnitude
magnitude = sqrt(A.x ^ 2 + A.y ^ 2);
// Use our rotate function to adjust A's rotation
angle_a = rotateTowards(angle_a, angle_b, 0.01);

// Set A's x/y as per the new angle and old magnitude
A.x = cos(angle_a) * magnitude;
A.y = sin(angle_a) * magnitude;

In the above example the vector would rotate 0.01 radians per execution, but in practice you'd want to use something like rpm * 60 * dt where dt is your delta time in seconds.

| improve this answer | |
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.