Understanding AI_Path's velocity calculation

Hey Aron,

I’m trying to understand how the target velocity is being calculated in AI_Path. I understand most of the code, but can’t quite understand what’s going on in this section (at the very bottom of CalculateVelocity():

	Vector3 forward = tr.forward;
	float dot = Vector3.Dot(dir.normalized, forward);
	float sp = speed * Mathf.Max(dot, minMoveScale) * slowdown;

	if (Time.deltaTime > 0) {
		sp = Mathf.Clamp(sp, 0, targetDist/(Time.deltaTime*2));
	}
	return forward*sp;

What exactly is this code doing? If we just wanted to calculate the modified speed (i.e. the speed adjusted for the slowdown), could we simply say sp = speed * slowdown?

Thanks!

PS: I’m pretty sure the line of code that goes:

	Vector3 dir = vPath[currentWaypointIndex] - vPath[currentWaypointIndex-1];

Is unecessary as you calculate the target position in the line just below it.

Hi

Here is an annotated version, hopefully this should clear up any confusion

// Get the forward direction of the transform component, this is the blue axis in the scene view
Vector3 forward = tr.forward;
// Calculate the cosine of the angle between the direction that we want to move in and the forward direction.
// This will be -1 if dir is directly opposite to our forward direction and +1 if it is in exactly the same direction
float dot = Vector3.Dot(dir.normalized, forward);
// Slow down the character if we are either close to the end point (the 'slowdown' variable will be small)
// or if we are not facing the direction that we want to move in (the 'dot' variable will be small or even negative).
// To ensure we always move slowly forwards we take the maximum of the dot variable and the minMoveScale variable
// which is a user defined constant. Usually something like 0.2 which means that the character should not be slowed down by more than 80% by not facing the correct direction.
float sp = speed * Mathf.Max(dot, minMoveScale) * slowdown;

// Avoid a division by zero in the code below
if (Time.deltaTime > 0) {
	// Make sure we don't overshoot the target point even if the fps is low.
	// This will make sure that we never move more than half the distance to the target point in a single frame
	sp = Mathf.Clamp(sp, 0, targetDist/(Time.deltaTime*2));
}
// Move in the forwards direction using a speed of 'sp' meters per second.
return forward*sp;