# Variable Projectile speed that changes based on distance from Target

I have an Issue where I want to change a Projectiles speed based on its distance from the target. I want it to be faster the further away from the target it is and slower the closer it gets to the target.

This is the code I am using now :

``````    public int damage;
public AnimationCurve speedCurve;
public float minSpeed, maxSpeed, speed;
public GameObject Target;

// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
transform.position = Vector3.MoveTowards(this.transform.position, Target.transform.position, speed);
transform.Rotate(0.0f, 0.0f, 1f);
}
``````

I have tried using animation curves along with other methods to solve this issue, but so far haven’t had any success.

Ok, so if you want to use an AnimationCurve to model your projectile speed, make sure that the interval is normalized [0,1] and then set the speed that you desire for that interval (IE: minSpeed could be at 0, maxSpeed at 1 or even at 0.7, however you desire). Then, we need to get the distance percentage from target (1 - we are at max distance, 0 - we hit the target) To do this we first calculate the initial distance and then in each frame we calculate the distance till we hit the target and we divide it by the initial distance, in orther to obtain that normalized percentage. The code is bellow

``````     public int damage;
public AnimationCurve speedCurve;
public float minSpeed, maxSpeed, speed;
public GameObject Target;

private float totalDistance;

// Start is called before the first frame update
void Start()
{
totalDistance = (transform.position - Target.transform.position).magnitude;
}

// Update is called once per frame
void Update()
{
var remainingDistance = (transform.position - Target.transform.position).magnitude;
speed = speedCurve.Evaluate(Math.Clamp01(remainingDistance / totalDistance))
transform.position = Vector3.MoveTowards(this.transform.position, Target.transform.position, speed);
transform.Rotate(0.0f, 0.0f, 1f);
}
``````

You could try something along these lines:

Math.Lerp(minSpeed, maxSpeed, distanceToTarget/maxDistance)

Lerp will pick a value between the first two arguments based on how big the third argument is. If the third argument is 0 you get minSpeed, if it’s 1 you get maxSpeed. So if you pass in the current distance divided by the distance at which you want max speed, you should get the desired behaviour.