Question

I have 3 values that determine an object's movement: velocity, acceleration, and maxVelocity. I also have a distance value that determines how close they are to their target (basically an X). This code runs each frame to determine actual movement based on the 3 values:

var velocityDelta = (Math.max(Math.min(velocity + (acceleration * 0.016), maxVelocity), -maxVelocity) - velocity) / 2;
velocity += velocityDelta;
var delta = velocity*0.016;
velocity += velocityDelta;
distance -= delta;

If that velocityDelta is a bit confusing it's basically this:

velocityDelta = velocity + (acceleration * 0.016);
if (velocityDelta > maxVelocity) velocityDelta = maxVelocity;
else if (velocityDelta < -maxVelocity) velocityDelta = -maxVelocity;
velocityDelta = (velocityDelta - velocity) / 2;

Now, assuming you can ONLY change the the value of acceleration, is there a way to calculate what acceleration you'll need in order to ensure that distance will end up at exactly 0? Meaning during one of the frames in which the above code is run, distance - delta == 0. So assume the code looks like this:

var distance = 300.5;
var velocity = 125.86;
var maxVelocity = 300;
while (distance != 0) {
    acceleration = ?
    var velocityDelta = (Math.max(Math.min(velocity + (acceleration * 0.016), maxVelocity), -maxVelocity) - velocity) / 2;
    velocity += velocityDelta;
    var delta = velocity*0.016;
    velocity += velocityDelta;
    distance -= delta;
}

What value would you put into acceleration to ensure that the loop doesn't run forever? Assuming distance/velocity/max can be any number that you can't change.

Was it helpful?

Solution

Your problem is pretty underconstrained. I'll suppose that the best solution is to decelerate (i.e. accelerate in the direction opposite to velocity) so that maxVelocity won't be a problem.

First, find out how many time intervals there will be before the object reaches the target (assuming no acceleration):

var dt = 0.016;
var jumps = distance/(dt * velocity);   <-- round DOWN

Then apply some basic physics to travel distance in that amount of time:

x = vt + at^2/2
a = 2(x-vt)/t^2
acceleration = 2*(distance - velocity*jumps*dt)/(jumps*dt*jumps*dt); 

This works pretty well. There's a slight kludge in there that bothers me a little, but I don't feel like tracking down right now-- it probably cancels out a kludge in the code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top