1
votes

I am trying to make a game by myself and I encountered a difficulty.

I have this object and I need it to accelerate towards a vector 3 point.

I tried using the Vector3.MoveTowards command, but the object moves with a constant velocity and stops at the destination.

What I need to do is have the object accelerate from 0 velocity towards a vector 3 point and not stop at the point, but continue at the same direction after it went through the point.

Does anyone know how to do this?

Thank you!

1

1 Answers

3
votes

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.