I’m trying to get my simulation to stop on a specific point. I have my starting position, an ending position, my current velocity and the time I’d like to take to get there. Since:
d = vt + (at^2)/2
I was figuring that
d = (end - start)
a = 2(d - vt) / t^2
but my end point is way off when I run it. I’ve tried using two simple updates, first:
v += a * dt
d += v * dt
and second:
d += v * dt + a * dt * dt / 2;
v += a * dt;
if that matters. Position in this case is 1d, so no need for crazy vector stuff. Any help would be greatly appreciated 🙂 Thanks!
(Edit: formatting)
(Edit2: corrected update #2)
(Edit3: updates now show dt instead of t)
We start at x_start (and t=0), with speed v_start, and we want to end at x_end, with velocity zero.
Since we have a constant acceleration, the average speed will be
v_start/2, which means we’ll reach x_end att_end = (x_end - x_start) / (v_start / 2).Okay, so then we can use
x(t) = x_start + v_start * t + at^2/2. As a sanity check, plug in t=0 and make sure you get x = x_start.Then plug in t_end and you can solve for a. I get
-v^2/(2D)where D isx_end - x_start. The negative sign just means you’re slowing down instead of speeding up.If you plug this into the original function you get:
If you have a counter that tells you the value of t (which will vary between 0 and t_end), you can simply move the object to the correct position at each moment.
Or (and this might make more sense, depending on the language, environment, etc.), you can calculate the instantaneous velocity each timestep by, and then the instantaneous position, following CoderTao’s answer.