- Home /
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???
Answer by Fabkins · Nov 02, 2011 at 12:26 AM
Comments seemed to have scrambled the format so putting it here instead with some extra comments.
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;
}
For the record, there is a term for this type of behavior. It's called "arrival". You can google a lot of vector movement formulae for your various use cases. This would be "vector movement arrival" and is likely to lead you to pages that list a bunch of other types of behaviors.
Answer by Fabkins · Nov 01, 2011 at 11:01 PM
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;
}
Thanks....
i was thinking more alon the lines of $$anonymous$$ax distance= speed 100% $$anonymous$$in distance = speed 25%
var dist=Vector3.Distance(me.position, ai.position);
if ( dist > $$anonymous$$aximumDistance) { aiSpeed = $$anonymous$$axSpeed; } else if ( dist < $$anonymous$$inimumDistance) { aiSpeed = $$anonymous$$inSpeed; } else { // This is the % ratio between $$anonymous$$ax and $$anonymous$$in distance
var distRatio=(dist - $$anonymous$$inimumDistance)/($$anonymous$$aximumDistance - $$anonymous$$inimumDistance);
// This is the extra speed above $$anonymous$$ speed he can go up too
var extraSpeed = $$anonymous$$axSpeed - $$anonymous$$inSpeed;
// Final calc aispeed = ( distRatio * extraSpeed) + $$anonymous$$inSpeed; }
Answer by Diekeke · Jun 21, 2013 at 06:11 PM
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! :D