Game Development Reference
In-Depth Information
Clamping the horizontal speed of an agent
Next, we want to clamp the speed of our agent. If you think about the forces being applied
to agents, acceleration changes will quickly cause the agent to move faster than their max-
imum speed allows.
When clamping the velocity, we only want to consider the agent's lateral velocity and ig-
nore any speed attained through gravity. To calculate this, we first take the agent's speed
and zero out all movement in the y axis. Next, we clamp the magnitude of the velocity with
the agent's maximum speed.
Before assigning the velocity back to the agent, we set back the change in velocity in the y
axis:
AgentUtilities.lua :
function AgentUtilities_ClampHorizontalSpeed(agent)
local velocity = agent:GetVelocity();
-- Store downward velocity to apply after clamping.
local downwardVelocity = velocity.y;
-- Ignore downward velocity since Agents never apply
downward
-- velocity themselves.
velocity.y = 0;
local maxSpeed = agent:GetMaxSpeed();
local squaredSpeed = maxSpeed * maxSpeed;
-- Using squared values avoids the cost of using the
square
-- root when calculating the magnitude of the velocity
vector.
if (Vector.LengthSquared(velocity) > squaredSpeed)
then
local newVelocity =
Vector.Normalize(velocity) * maxSpeed;
-- Reapply the original downward velocity after
Search WWH ::




Custom Search