If somebody wanted to develop a system between two intersecting rectangles so that the rectangles would, in a gradual process, push eachother away from one another until no longer intersecting, with the repelling force being stronger depending upon how deep the intersection is... what would the math look like?

  • \$\begingroup\$ Should they accelerate until not intersecting? And should they slow down gradually to stop just when they stop intersecting? \$\endgroup\$ Sep 27, 2012 at 21:39
  • \$\begingroup\$ Yes, they should accelerate until not intersecting- as far as slowing down once they stop intersecting, the world's friction would take care of that once acceleration is no longer applied to the rectangles from their intersection. \$\endgroup\$ Sep 27, 2012 at 22:02

1 Answer 1


dx:Number = a.x - b.x; //distance by x
dy:Number = a.y - b.y;
distance:Number = Math.sqrt ( dx*dx + dy*dy );

If you want to simulate magnet behavior, you want to base forces on distance between them. Physics say so:

formula for magnetic force

But you will be fine with:

force = Math.floor ( MAX_FORCE / distance );

And then you need to use trigonometry to apply force as velocity change:

var angle:Number = Math.Atan2 ( dy, dx );
var x_speed:Number = force * Math.cos ( angle );
var y_speed:Number = force * Math.sin ( angle );

a.vx += x_speed;
a.vy += y_speed;
b.vx -= x_speed;
b.vy -= y_speed;

//and of course a.x += a.vx etc.
  • \$\begingroup\$ After implementing this to my game, it -almost- works, but I am experiencing an issue: Object1 is a player character and object2 is a dummy box that does nothing other than sit in place unless outside forces are applied to it; when object1 is moved into object2, and presses too far into object2, first it stops moving (desirable considering its intersection has gone too far, and is being repelled too hard to continue pushing any further) but then when object1 stops accelerating into object2, object1 is repelled out of object2, but then object2 sort of 'sticks' to object1, and they both scoot \$\endgroup\$ Sep 27, 2012 at 22:12
  • \$\begingroup\$ and they both scoot away in the direction opposite what object1 was originally pushing from to begin with. I have no idea what would cause this behavior? \$\endgroup\$ Sep 27, 2012 at 22:14
  • \$\begingroup\$ I need to see your code. \$\endgroup\$ Sep 27, 2012 at 22:22
  • 2
    \$\begingroup\$ Never mind, thank you again for your help and willingness to have a look at my code. My aforementioned problem was due to my own faulty handling of friction, I debugged and located it and handled it. Everything works great, thanks again! :) \$\endgroup\$ Sep 27, 2012 at 22:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .