In a 2D world I have 2 fixed planets. They each have a script attached (the same script) that adds a force to an asteroid like rigidbody object within the world. The magnitude of their forces is based on the scale of the planet and the distance away from the rigidbody.

Here is the code:

``````var ball : GameObject;
var pullForce : int = 1;

function FixedUpdate () {
var netPullForce = (transform.localScale.x * pullForce) * (1 / Vector3.Distance(ball.transform.position, transform.position));
var targetDir = transform.position - ball.transform.position;
print(netPullForce);
}
``````

After testing 2 planets the same distance from the rigidbody I successfully concluded that the rigidbody will move toward the planet with the largest scale.

However, the problem arrises when I attempt to add force to the rigidbody based on distance from the planets.

I made both planets a scale of 1 to ensure fair testing.
I then placed the rigidbody between the planets.
Planet 1 is 2 units away from the rigidbody, planet 2 is 1 unit away from the rigid body.
Therefore the rigidbody SHOULD move toward planet 2, as it is the closer and should have the larger force applied.
However is simply does not move at all, as if distance is not a factor in the code.

the variable ‘netPullForce’ which controls how much force to add based on the distance away and scale of the planet seems to be working fine. Planet 1 (the further away) has a netPullForce value of only 0.5 while planet 2 (The closer planet) has a netForcePull value of 1.0. Therefore it should move toward planet 2.

Due to the netPullForce variable appearing to be correct in its values, I can only see the problem being something to do with the line of code:

``````ball.rigidbody.AddForce(targetDir * netPullForce);
``````

and my understanding of how this AddForce function works.

Been trying for quite some time now and I just cant work it out. Any help would be appretiated.

Thanks.

Hmm, the logic seems to be fine.

I see 3 potential points of problem there:

One, you should use AddForce with the ForceMode.Acceleration parameter. Gravity affects all bodies the same way, regardless of mass.

Two, you should change that pullForce variable from int to float. It may be causing a rounding problem with varying scale planets (you wouldn’t notice it if the planet was of scale 1.0)

And lastly, you might wanna try normalizing the target’s direction too. (get it down to a unit vector, then multiply it by gravity strength)

``````var ball : GameObject;
var pullForce : float = 1;

function FixedUpdate () {
var netPullForce = (transform.localScale.x * pullForce) * (1 / Vector3.Distance(ball.transform.position, transform.position));
var targetDir = (transform.position - ball.transform.position).normalized;