Advertisement

equations of motion for position dependent acceleration

Started by October 18, 2015 09:16 PM
2 comments, last by JoeJ 9 years, 3 months ago
Hi,

i'd like to calculate position, velocity and acceleration at a given time
when acceleration depends linearily on position.

Here is some code using integration to show what i mean:

	float start = 0.8f;
	float accFactor = -5.0f;
	float timestep = 0.008f;
	float p = start;
	float v = 0;
	float a;
	for (float t = 0; t <= 2.0f; t += timestep) // position dependent acc
	{
		a = (1.0f - p) * accFactor;
		v += a * timestep;
		p += v * timestep;

		float aA = how to calculate acceleration without integration? 
		float vA = ?
		float pA = ?
		
		RenderPoint (2, sVec3 (t, 5+aA, 0), 1,1,1);		
	}

Here is another snippet just for reference with constant acceleration.
No problem there to claculate position and velocity.

p = start;
	v = 0;
	a = -5.0f;
	for (float t = 0; t <= 2; t += timestep) // constant acc
	{
		v += a * timestep;
		p += v * timestep;

		float pA = start + 0.5f * a * t*t;
		float vA = a * t;
	}
The jpg shows plots of this code, pos = red, vel = green, acc = blue (constant acc right).

Any help appreciated!
Wolfram Alpha knows how to solve that differential equation (I do too, but it's easier to post this link): http://www.wolframalpha.com/input/?i=x%27%27+-+kx+%3D+0
Advertisement
Here's some code. I am not sure how general it is (at least it won't work with positive values of accFactor), but it works for your case:

#include <iostream>
#include <cmath>

int main() {
  float start = 0.8f;
  float accFactor = -5.0f;
  float timestep = 0.008f;
  float p = start;
  float v = 0.0f;
  float a;

  float const S = std::sqrt(-accFactor);
  float const c1_plus_c2 = 1.0f - p;
  float const c1_minus_c2 = -v / S;
  float const c1 = 0.5f * (c1_plus_c2 + c1_minus_c2);
  float const c2 = 0.5f * (c1_plus_c2 - c1_minus_c2);

  for (float t = 0; t <= 2.0f; t += timestep) {
    a = (1.0f - p) * accFactor;
    v += a * timestep;
    p += v * timestep;

    float pA = 1.0f - c1 * std::exp(S * t) - c2 * std::exp(-S * t);
    float vA = - c1 * S * std::exp(S * t) + c2 * S * std::exp(-S * t);
    float aA = (1.0f - pA) * accFactor;

    std::cout << p << ' ' << v << ' ' << a << "     " << pA << ' ' << vA << ' ' << aA << '\n';
  }
}

Awesome! Thank you biggrin.png

This topic is closed to new replies.

Advertisement