# Using AddForce() to implement a follow script

Not looking for an implementation to the problem (although that would be good :P), mainly looking to be pointed in the right direction for solving it.

Basically, I want to have various game objects following a single game object, using rigidbody.AddForce(). This is to allow for realistic physics simulations as collisions will be a key part of this and using anything but rigidbody.AddForce() doesn't really allow for it.

I have been working on implementing this, but the GameObjects which are following always tend to overshoot their target, or they can't quite stop in time when applying reverse force to slow them.

As I've said, I'm mainly looking to be pointed in the right direction, be it some mathematical formulae that I require, or another method that I am overlooking. With that said, a very simple implementation to build-on would be awesome.

All help is greatly appreciated!

Thanks!

With AddForce you are not going to have much control over where your character is going to stop. You are going to want to implement your own velocity change calculations on your RigidBody instead of relying on AddForce().

For example:

float Speed = 10;
Vector2 Direction = CalculationCurrentDirection();

RigidBody.velocity += Direction * Speed * Time.deltaTime;


This will still allow your physics engine to do its thing, and will allow you to be able to control your character a lot better. You can then stop your character when he is near your target position.

Sample implementation:

Rigidbody2D RigidBody;

bool ArrivedAtTarget;
float Speed = 10;
float Threshold = 1;

//random target
Vector2 Target = new Vector2(10, 5);

void Start() {
RigidBody = GetComponent<Rigidbody2D> ();
}

void Update() {
if (!ArrivedAtTarget) {
//Get Direction to go straight towards this target
Vector2 Direction = Target - RigidBody.position;
Direction.Normalize();
}
}

//Check position in FixedUpdate
void FixedUpdate() {
if ((RigidBody.position - Target).magnitude <= Threshold) {
ArrivedAtTarget = true;
RigidBody.velocity = Vector2.zero;
}

//Set RigidBody Velocity
RigidBody.velocity += Direction * Speed * Time.deltaTime;
}