Hello all,
I'm trying to implement some steering behaviors in a game I'm working on, and I'm having a little trouble getting the "Arrive" behavior working properly. The function I have here is supposed to return a steering force that will cause the agent to slow down and stop at the TargetPos grcefully, however the way it's working now causes him to overshoot the target over and over before finally coming to a stop. I've tried tweaking everything I can think of, but I just can't seem to get the agent to behave the way I want.
One solution I've seen involves a "braking radius" that kicks in when the agent is close to the target, but the functionality I'm after shouldn't need to involve a radius; I want the agent to slow himself based on his distance to the targetPos.
Here's the function in question. The Deceleration parameter is simply an enumerated int 1-3.
private Vector2 Arrive(Vector2 Targetpos, Deceleration deceleration) {
Vector2 ToTarget = sub(Targetpos, agentPos);
//calculate the distance to the target
float dist = ToTarget.len();
if (dist > 0.2f) {
final float DecelerationTweaker = 0.3f;
//calculate the speed required to reach the target given the desired
//deceleration
float speed = dist / ((float) deceleration.value() * DecelerationTweaker);
//make sure the velocity does not exceed the max
speed = Math.min(speed, agentMaxSpeed);
Vector2 DesiredVelocity = mul(ToTarget, speed / dist);
return sub(DesiredVelocity, agentVelocity);
}
return new Vector2(0, 0);
}
And here's the code that updates my agent's position:
float agentMass = 1f;
Vector2 agentForce = new Vector2(0f,0f);
float agentMaxSpeed = 1.6f;
float agentMaxForce = 5f;
agentForce = calculate(); //calls Arrive function
agentAccel = div(agentForce, agentMass);
agentVelocity.add(agentAccel.x * deltaTime, agentAccel.y * deltaTime );
agentVelocity.truncate(agentMaxForce);
//update the heading if the vehicle has a non zero velocity
if (agentVelocity.lenSq() > 0.00000001f) {
agentHeading = vec2Normalize(agentVelocity);
agentHeadingAngle = agentHeading.angle();
}
agentPos.add(agentVelocity.x * deltaTime, agentVelocity.y * deltaTime);
Thanks in advance for the help. This problem has been giving me a headache for days and I'm sure it's just something very small I'm missing.