So I'm working on a program that's trying to simulate universal gravitation ((mass of one body * mass of another body)/distance between them^2). I've got collision worked out, movement is done by adding XSpeed and YSpeed to the X and Y coordinates of the player body (the only one that moves in the sim). The other five bodies, planets, are stationary, and all pull the player body simultaneously according to the above formula.
Only, I can't seem to get the actual formula to apply well. It's spazzing out, and I can't seem to figure out why. I think part of it is that when the player body is on an axis with one of the bodies, the formula divides by zero and the player body warps the hell away.
stage.addEventListener(Event.ENTER_FRAME, accelPlayer)
function accelPlayer(e:Event):void{
if(Mode==true){
p1.x += playerXSpeed/pm
p1.y += playerYSpeed/pm
}
if((dist1>(pr+b1r)) && (dist2>(pr+b2r)) && (dist3>(pr+b3r)) && (dist4>(pr+b4r)) && (dist5>(pr+b5r))){
Mode=true
playerXSpeed =(b1m*pm/(dist1X*dist1X))+(b2m*pm/(dist2X*dist2X))+(b3m*pm/(dist3X*dist3X))+(b4m*pm/(dist4X*dist4X))+(b5m*pm/(dist5X*dist5X))
playerYSpeed =(b1m*pm/(dist1X*dist1X))+(b2m*pm/(dist2X*dist2X))+(b3m*pm/(dist3X*dist3X))+(b4m*pm/(dist4X*dist4X))+(b5m*pm/(dist5X*dist5X))
//I think the problem is that when it's on an X or Y Coord with one of the bodies, it divides by zero and warps the fuck away
}
else if(dist1<=(pr+b1r) || dist2<=(pr+b2r) || dist3<=(pr+b3r) || dist4<=(pr+b4r) || dist5<=(pr+b5r)){
Mode = false
}
}
Key:
p1 is the player body's sprite.
pr is the player body's radius
pm is the player body's mass.
b#r is the radius of that body.
b#m is the mass of that body.
dist#X is the distance between that body and the player body on the X coordinate, vice versa for Y.
Mode is the boolean that determines collision; it starts true, becomes false and stops motion when there's a collision.
Note: The registration points for each sprite are at their centers. Each dist variable is positive when the player coord is greater than the respective body's coord (so, dist1X is positive when player is to the right of body1).
Also note: the radii are generated randomly when the program is run, and the masses are computed accordingly.
Basically, that should make the vectored movement of the player body equal to the sum of all the forces applied to it by the five planetary bodies. Only, nothing works, I don't know how to avoid division by zero. Any help would be tremendously appreciated :)