I have implemented a movement system based on steering behaviors: http://gamedevelopment.tutsplus.com/series/understanding-steering-behaviors--gamedev-12732 where each object has vec2 position, velocity, desiredPosition with 2 constants: maxspeed and acceleration. In each game step, the object's position is updated as follows:
vec2 desiredVel = this.desiredPos - this.position;
desiredVel.truncate(this.maxSpeed);
vec2 steeringForce = desiredVel - this.velocity;
steeringForce.truncate(this.acceleration);
this.velocity += this.steeringForce * dt;
this.velocity.truncate(this.maxSpeed);
this.position += this.velocity * dt;
The problem is stopping. I have been stopping by using a scaling factor that reduces the desiredVel when the object is within a certain distance of the target position:
var dist = desiredVel.length;
if (dist < this.maxSpeed * this.maxSpeed / this.acceleration){
this.desiredVel *= dist/this.maxSpeed;
}
This goes between the desiredVel calculation and steering force calculation.
Unfortunately, this method is not very exact. Sometimes the object will overshoot its destination and sometimes it will slow down way before the destination is reached. Is there a way to make the object stop on the destination point? That is, it should not overshoot nor slow down prematurely.
Edit: and yes I have seen the arrival section in the link I posted above and it shares this same inexactness. What I want I guess is for the path to look more realistic. That is the object accelerates at the start of path to its max speed then it decelerate at the right timing so that it stops at the destination exactly. (or close enough)
And 2ndly, I also want to know the time it takes for an object to reach from pointA to pointB before the object takes its path. The maxspeed and acceleration is constant and there are no other forces acting on the object within the path. How can i calculate the time?