Sunday, September 20, 2015

xna - 2D Magnet-like repelling behavior


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?



Answer




a:Object;
b:Object;

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.

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...