# Speed based on Distance

Speed based on Distance…
I am working on a side scrolled Ai.
What I want to do is as Ai get closer to player he will slow down. As of right now I am using few IF statement.

Is there a way to make it more automatic??
Maybe few ideas on how to do it???

``````var dist=Vector3.Distance(me.position, ai.position);

if ( dist > MaximumDistance)
{
// AI is far away give him Max speed
aiSpeed = MaxSpeed;
}
else if ( dist < MinimumDistance)
{
// AI is closer than minimum distance give him Min speed
aiSpeed = MinSpeed;
}
else
{
// AI is between Max/Min distance so give him a speed proportional
// between Min and Max speed

// This is the % ratio between Max and Min distance

var distRatio=(dist - MinimumDistance)/(MaximumDistance - MinimumDistance);

// This is the extra speed above min speed he can go up too

var diffSpeed = MaxSpeed - MinSpeed;

// Final calc
aispeed = ( distRatio * diffSpeed) + MinSpeed;
}
``````

This what I would do. Assuming that beyond a given distance you want the AI to go at maximum speed and grind to a halt when he reaches you I do something like:

``````var dist=Vector3.Distance(me.position, ai.position);

if ( dist > MaximumDistance)
{
aiSpeed = MaxSpeed;
}
else
{
aiSpeed = ( dist / MaximumDistance ) * MaxSpeed;
}
``````

Here’s a faster way to do it, just get the distance between AI and Player, and make the speed equal to it (aiSpeed = dist), this way, the AI will move towards the player gradually from fast to slow until it reaches the player, and if you want that the AI moves from slow to fast, just make the speed equals the max distance you get minus the distance, example: aiSpeed = 50 - dist
So there you have it, hope this helps you!