Perform these steps in a method that is called in the Update
or FixedUpdate
method. FixedUpdate
is recommended if you are using rigid bodies.
First, you need to find the direction from your position to the point, and define a velocity
instance variable in your script if not using Rigid Bodies. If you are using a Rigidbody
, use rigidbody.velocity
instead. target
is the Vector3
position that you want to accelerate towards.
// Use rigidbody.velocity instead of velocity if using a Rigidbody
private Vector3 velocity; // Only if you are NOT using a RigidBody
Vector3 direction = (target - transform.position).normalized;
Then you need to check if we have already passed the target or not. This check makes sure that the velocity remains the same
// If our velocity and the direction point in different directions
// we have already passed the target, return
if(Vector3.Dot(velocity, direction) < 0)
return;
Once we have done this we need to accelerate our Transform
or Rigidbody
.
// If you do NOT use rigidbodies
// Perform Euler integration
velocity += (accelMagnitude * direction) * Time.deltaTime;
transform.position += velocity * Time.deltaTime;
// If you DO use rigidbodies
// Simply add a force to the rigidbody
// We scale the acceleration by the mass to cancel it out
rigidbody.AddForce(rigidbody.mass * (accelMagnitude * direction));
I recommend that you use a Rigidbody
since it makes much more sense when doing something like this.