How to Make rigidbody.AddForce be Less the Further a RigidBody gets from an Object?

Hey guys,

I have an object that needs to slow down the further it gets away from the ground. Using:

rigidbody.AddForce (0, 10, 0);

works fine, but I need it to be:

rigidbody.Addforce(0,0,0)

when it gets to a certain height.

It needs to be done gradually, not just stop when it reaches said height.

Any ideas on how to do this?

Thanks!

Vector3.Distance returns a float, or you can subtract the Y axes from 2 positions, and use that to multiply the force.

An example:

float target_height;
Transform obj;

void FixedUpdate(){
    float d = Vector3.Distance(obj.position, new Vector3(obj.position.x, target_height, obj.position.z);
    //or
    float d = target_height - obj.y;
    obj.rigidbody.AddForce(0, 10 * d, 0);
}

The closer you get to the target height the value will eventually go below 1, but it will also be above 1 when you are far from it which will cause the force to increase. You can limit it with Mathf.Min though. Vector3.Distance will start to increase again if you go above the height so it’s probably not the best in this case, the subtraction will go negative once you pass the height but it can be prevented with Mathf.Max

float d = Mathf.Max(target_height.y - obj.y, 0);

I think you could change the ForceMode to VelocityChange.

rigidbody.AddForce(0, 10, 0, ForceMode.VelocityChange );

and employ the tactic below fomo Josh707.

float target_height;
Transform obj;
 
void FixedUpdate(){
float d = Vector3.Distance(obj.position, new Vector3(obj.position.x, target_height, obj.position.z,ForceMode.VelocityChange);
//or
float d = target_height - obj.y;
obj.rigidbody.AddForce(0, 10 * d, 0, ForceMode.VelocityChange);
}