Reputation: 87
Im making a game where I use objects that have their own gravity. Im using the Vector2.Distance method. When the objects start going closer to eachother, the distance gets smaller, but when it gets to 2 it starts to get bigger again.
foreach (Rigidbody2D body in allRigidBodies)
{
if (body.gameObject.layer == 8 && body.name != ThisBodyName)
{
AvrgPosition2D += body.position;
AvrgMass += body.mass;
count++;
}
}
AvrgPosition2D = AvrgPosition2D / count;
AvrgPosition3D = AvrgPosition2D;
distance = Vector2.Distance(AvrgPosition3D, ThisBodyRB.position);
force = GravConstant * AvrgMass * ThisBodyMass / (distance * distance);
ThisBodyRB.AddForce(AvrgPosition3D * (float)force * Time.deltaTime);
AvrgMass = 0;
AvrgPosition2D -= AvrgPosition2D;
count = 0;
I also tried (AvrgPosition - ThisBodyRB.position).magnitude, but that didnt change anything.
Also, I have this script on 2 objects, but they dont output the same distance.
Upvotes: 1
Views: 643
Reputation: 46
Your line:
AvrgPosition2D = AvrgPosition2D - ThisBodyRB.position;
Is likely the problem. The positions you are comparing are the location of the body in question and the average location of all bodies - the location of the body in question.
As far as I can tell this line is not necessary at all since you are not considering the location of the current body anyway when getting the average location.
Upvotes: 3