Simple physics-based movement - math

I'm working on a 2D game where I'm trying to accelerate an object to a top speed using some basic physics code.
Here's the pseudocode for it:
const float acceleration = 0.02f;
const float friction = 0.8f; // value is always 0.0..1.0
float velocity = 0;
float position = 0;
move()
{
velocity += acceleration;
velocity *= friction;
position += velocity;
}
This is a very simplified approach that doesn't rely on mass or actual friction (the in-code friction is just a generic force acting against movement). It works well as the "velocity *= friction;" part keeps the velocity from going past a certain point. However, it's this top speed and its relationship to the acceleration and friction where I'm a bit lost.
What I'd like to do is set a top speed, and the amount of time it takes to reach it, then use them to derive the acceleration and friction values.
i.e.,
const float max_velocity = 2.0;
const int ticks; = 120; // If my game runs at 60 FPS, I'd like a
// moving object to reach max_velocity in
// exactly 2 seconds.
const float acceleration = ?
const float friction = ?

I found this question very interesting since I had recently done some work on modeling projectile motion with drag.
Point 1: You are essentially updating the position and velocity using an explicit/forward Euler iteration where each new value for the states should be a function of the old values. In such a case, you should be updating the position first, then updating the velocity.
Point 2: There are more realistic physics models for the effect of drag friction. One model (suggested by Adam Liss) involves a drag force that is proportional to the velocity (known as Stokes' drag, which generally applies to low velocity situations). The one I previously suggested involves a drag force that is proportional to the square of the velocity (known as quadratic drag, which generally applies to high velocity situations). I'll address each one with regard to how you would deduce formulas for the maximum velocity and the time required to effectively reach the maximum velocity. I'll forego the complete derivations since they are rather involved.
Stokes' drag:
The equation for updating the velocity would be:
velocity += acceleration - friction*velocity
which represents the following differential equation:
dv/dt = a - f*v
Using the first entry in this integral table, we can find the solution (assuming v = 0 at t = 0):
v = (a/f) - (a/f)*exp(-f*t)
The maximum (i.e. terminal) velocity occurs when t >> 0, so that the second term in the equation is very close to zero and:
v_max = a/f
Regarding the time needed to reach the maximum velocity, note that the equation never truly reaches it, but instead asymptotes towards it. However, when the argument of the exponential equals -5, the velocity is around 98% of the maximum velocity, probably close enough to consider it equal. You can then approximate the time to maximum velocity as:
t_max = 5/f
You can then use these two equations to solve for f and a given a desired vmax and tmax.
Quadratic drag:
The equation for updating the velocity would be:
velocity += acceleration - friction*velocity*velocity
which represents the following differential equation:
dv/dt = a - f*v^2
Using the first entry in this integral table, we can find the solution (assuming v = 0 at t = 0):
v = sqrt(a/f)*(exp(2*sqrt(a*f)*t) - 1)/(exp(2*sqrt(a*f)*t) + 1)
The maximum (i.e. terminal) velocity occurs when t >> 0, so that the exponential terms are much greater than 1 and the equation approaches:
v_max = sqrt(a/f)
Regarding the time needed to reach the maximum velocity, note that the equation never truly reaches it, but instead asymptotes towards it. However, when the argument of the exponential equals 5, the velocity is around 99% of the maximum velocity, probably close enough to consider it equal. You can then approximate the time to maximum velocity as:
t_max = 2.5/sqrt(a*f)
which is also equivalent to:
t_max = 2.5/(f*v_max)
For a desired vmax and tmax, the second equation for tmax will tell you what f should be, and then you can plug that in to the equation for vmax to get the value for a.
This seems like a bit of overkill, but these are actually some of the simplest ways to model drag! Anyone who really wants to see the integration steps can shoot me an email and I'll send them to you. They are a bit too involved to type here.
Another Point: I didn't immediately realize this, but the updating of the velocity is not necessary anymore if you instead use the formulas I derived for v(t). If you are simply modeling acceleration from rest, and you are keeping track of the time since the acceleration began, the code would look something like:
position += velocity_function(timeSinceStart)
where "velocity_function" is one of the two formulas for v(t) and you would no longer need a velocity variable. In general, there is a trade-off here: calculating v(t) may be more computationally expensive than simply updating velocity with an iterative scheme (due to the exponential terms), but it is guaranteed to remain stable and bounded. Under certain conditions (like trying to get a very short tmax), the iteration can become unstable and blow-up, a common problem with the forward Euler method. However, maintaining limits on the variables (like 0 < f < 1), should prevent these instabilities.
In addition, if you're feeling somewhat masochistic, you may be able to integrate the formula for v(t) to get a closed form solution for p(t), thus foregoing the need for a Newton iteration altogether. I'll leave this for others to attempt. =)

Warning: Partial Solution
If we follow the physics as stated, there is no maximum velocity. From a purely physical viewpoint, you've fixed the acceleration at a constant value, which means the velocity is always increasing.
As an alternative, consider the two forces acting on your object:
The constant external force, F, that tends to accelerate it, and
The force of drag, d, which is proportional to the velocity and tends to slow it down.
So the velocity at iteration n becomes: vn = v0 + n F - dvn-1
You've asked to choose the maximum velocity, vnmax, that occurs at iteration nmax.
Note that the problem is under-constrained; that is, F and d are related, so you can arbitrarily choose a value for one of them, then calculate the other.
Now that the ball's rolling, is anyone willing to pick up the math?
Warning: it's ugly and involves power series!
Edit: Why doe the sequence n**F** in the first equation appear literally unless there's a space after the n?

velocity *= friction;
This doesn't prevent the velocity from going about a certain point...
Friction increases exponentially (don't quote me on that) as the velocity increases, and will be 0 at rest. Eventually, you will reach a point where friction = acceleration.
So you want something like this:
velocity += (acceleration - friction);
position += velocity;
friction = a*exp(b*velocity);
Where you pick values for a and b. b will control how long it takes to reach top speed, and a will control how abruptly the friction increases. (Again, don't do your own research on this- I'm going from what I remember from grade 12 physics.)

This isn't answering your question, but one thing you shouldn't do in simulations like this is depend on a fixed frame rate. Calculate the time since the last update, and use the delta-T in your equations. Something like:
static double lastUpdate=0;
if (lastUpdate!=0) {
deltaT = time() - lastUpdate;
velocity += acceleration * deltaT;
position += velocity * deltaT;
}
lastUpdate = time();
It's also good to check if you lose focus and stop updating, and when you gain focus set lastUpdate to 0. That way you don't get a huge deltaT to process when you get back.

If you want to see what can be done with very simple physics models using very simple maths, take a look at some of the Scratch projects at http://scratch.mit.edu/ - you may get some useful ideas & you'll certainly have fun.

This is probably not what you are looking for but depending on what engine you are working on, it might be better to use a engine built by some one else, like farseer(for C#).
Note Codeplex is down for maintenance.

Related

equation to get curve for simulating friction for a game

I want to very roughly simulate friction on particles from a top-down point of view. The particles should tend to come to a halt when they are going slow and experience less friction (relative to their velocity) the faster they are going. It should look something like this...
At the moment friction (a force applied to the particles every frame) = -(velocity*constant1 - velocity^2*constant2 )*deltatime
Can someone suggest a better way of doing this?
Usual friction
Usually friction is caused by speed and modeled in simple models by something like, say, - c v^2.
That means that if your particles have a force attracting them (e.g. gravity), then at some point friction evens it out and your particles reach a maximum constant velocity.
With the friction formula in your example, it eventually decreases and even reaches a positive value for big enough velocities, thus pushing the particles in the direction of their speed, which is kind of strange. In any case, friction forces that do not monotonously increase with speed are suspect.
The behaviour you describe by saying "experience less friction relative to their velocities the faster they are going", can be expressed mathematically by saying that you want a function that diverges less quickly than the identity. Formally, you are looking for a function f(x) such that f(x)/x converges towards 0 when x goes to infinity.
Let us leave aside functions that converge to a finite value (possibly 0), as they don't seem intuitive : the faster you go, the more friction you should have.
Functions you can use
Functions that diverge slower than x but still diverge are typically the powers of x with degrees in ]0,1[ (0 and 1 excluded). A good example is 0.5, a.k.a the square root of x.
Furthermore, another good fit is the log function, that diverges very slowly.
Then you can take any linear combination of the above, and even powers of the log.
Behaviour for small velocities
Now on your graph, the red line is always below the grey one, which isn't the case for a function x^a as described above. You probably want something that is 0 in x=0, since it doesn't make much sense even with your model to see a particle turn around and go back when it reaches speed 0. To comply to both requirements, you again have several options.
piecewise functions. Trivial, possibly easy to compute. Say you use x^0.83 on the interval [1,+inf[ and something that is 0 in x=0 and 1^0.83=1, in x=1, on the interval [0,1[. Typically something as trivial as x itself.
shifting the function, typically by 1 (that is enough for all the cases we look at). For the log this is pretty straightforward, since it diverges towards -inf in 0, and is 0 in 1, you should for your use never take log(x) but rather log(1+x). For powers, they behave like we want ("below the red line") for x > 1. To keep the property of a null friction when x=0, you need to shift in a fashion like : f(x)=(1+x)^a-1 with a in ]0,1[
Customizing to your taste
Now that you have all this, I would recommend you to try to plot a few of these functions. Pick the one that seems the most appropriate, you can typically chose how slow to increase by picking either the log (as slowest) or any power function (knowing that the bigger the power, the faster the increase in friction relative to velocity). You can also stretch the curve to increase faster or slower but keep the same "curvature", by dilating the curve, i.e. replace x by x/a or a * x. For example, with x^0.8, you can get this function : http://fooplot.com/plot/b7a0whkcdz
Only you know what kind of forces apply on the particles (which is with what you should compare the output values of the function, thus the f(x)), and what velocities are typical for the particles (thus over which x your function should span with acceptable values), so I cannot help you with that.
Then try some experiments with your game to adjust your parameters, and voilà ! You're done.
Some basic physic equations will help us.
Assuming we only deal with basic movement, with no external forces, it should go like this (the following calculation are there to clarify the final equation, you can skip this part):
Y-Axis forces: Normal(N) up, Gravitation(mg) down -> N = mg
X-Axis forces: Friction force to the left (or right), nothing to the other side -> -F(friction) = ma , F(friction) = N * μ(COF) -> F(friction) = mg * μ -> - mg * μ = ma
-> a = - μ * g ; v = v0 + at -> v = v0 - t(μ * g) .
V - the velocity of the object at time t = v(t) [Measuring in m/s].
V0 - The starting velocity of the object [Measuring in m/s].
t - Time passed since the starting of the movement [Measuring in s].
μ - Coefficient of Friction, a constant which represents how rough the surface is (0 - no friction at all) [Measuring in NaN - no units for COF].
g - Acceleration of Gravity (Constant) [Measuring in m/s^2], on Earth it's 9.81 m/s^2, but you can use 10.
Assuming μ to be 0.25 (COF of wood), the equation is:
V(t) = v0 - 2.5t

Closing towards a point, independent of the frame rate?

I'm making a Camera class in 3D that closes in towards a point, slowing down and easing into stopping. To do this regularly is pretty simple:
// positions are vectors, dampening is a scalar, usually set to ~0.9
currentPosition += (targetPosition - currentPosition) * dampening;
However, this is locked to the framerate, assuming it's executed exactly once per frame.
How would one best implement this behaviour that's dependent on time, instead of frame rate or times executed?
A short experiment (and if you need a bit of induction) shows that after n frames you are at
targetPosition*(1 - (1 - dampening)^n) + currentPosition*(1 - dampening)^n
so to make this time-dependent, write
targetPosition*(1 - pow(1 - dampening, t)) + currentPosition*pow(1 - dampening, t)
where dampening is now per unit of time, and time might even be fractional.
Your question reminds me of Calculate speed by distance and friction.

How do I correctly use Recursion in MATLAB?

I have a simple m file that I have created as a recursive function:
function[velocity] = terminal(m,c,t,vi)
%inputs:
% m = mass
% c = coeffcient of drag
% t = time
% vi = initial velocity
if t==18, velocity = vi+(9.8-c/m*(vi))*2;
return
end
velocity = vi+(9.8-c/m*(vi))*2;
velocity %used to print out velocity for debugging
terminal(m,c,t+2,velocity);
end
The calculation of velocity is being done correctly as it prints out every recursion. However the "ans" that is returned at the end is the first calculated value of recursion. My question is how do I correctly setup a matlab function recursively? Or can it be done, and is it better to use a loop?
Although my answer will stray away from programming and into the realm of calculus, it should be noted that you can solve your problem both without recursion or a loop since you can exactly solve for an equation v(t) using integration. It appears that you are modeling Stokes' drag on a falling body, so you can use the fourth formula from this integration table to compute a final velocity vFinal that is achieved after falling for a time tDelta given a starting velocity vInitial. Here is the resulting formula you would get:
vFinal = 9.8*m/c + (vInitial - 9.8*m/c)*exp(-c*tDelta/m);
This will be a more accurate answer than approximating vFinal by making sequential steps forward in time (i.e. the Euler method, which can display significant errors or instabilities when the time steps that are taken are too large).
Bear with me, haven't done a lot of Matlab for some time now.
But I would simply call your function iteratively:
velocity = vi
for t = 0:2:18
velocity = velocity+(9.8-c/m*(velocity))*2;
end
Then for each instance of t it would calculate velocity for a given initial velocity and update that value with it's new velocity.
To have it take incremental steps with a size of 2, simply add your step size to it.
Updated in response to the comments
velocity = terminal(m,c,t+2,velocity)
should work.
The problem with recursion here is it adds function call overhead for each time through. This will make your code far slower and less efficient in matlab. Use a loop instead and you will be far ahead of things. Yes, there are cases where recursion is a valuable tool. But in many cases a carefully written loop is the better solution.
Finally, when you DO use recursion, learn when to apply tools like memoization to improve the behavior of the algorithm. Memoization simply means to not recompute that which you have already done. For example it is possible to use recursion for a fibonacci sequence, but this is a terribly inefficient way to do so.
The return value of your function is velocity. Matlab will return the last value assigned to velocity in the function body. Even though velocity is assigned deeper into the recursion, this doesn't matter to Matlab.
velocity in the next call to terminal() is a different variable!
Changing the final line to
function[velocity] = terminal(m,c,t,vi)
%inputs:
% m = mass
% c = coeffcient of drag
% t = time
% vi = initial velocity
if t==18, velocity = vi+(9.8-c/m*(vi))*2;
return
end
velocity = vi+(9.8-c/m*(vi))*2;
velocity %used to print out velocity for debugging
velocity = terminal(m,c,t+2,velocity);
end
Gives the expected result.

Using an epsilon value to determine if a ball in a game is not moving?

I have balls bouncing around and each time they collide their speed vector is reduced by the Coefficient of Restitution.
Right now my balls CoR for my balls is .80 . So after many bounces my balls have "stopped" rolling because their speed has becoming some ridiculously small number.
In what stage is it appropriate to check if a speed value is small enough to simply call it zero (so I don't have the crazy jittering of the balls reacting to their micro-velocities). I've read on some forums before that people will sometimes use an epsilon constant, some small number and check against that.
Should I define an epsilon constant and do something like:
if Math.abs(velocity.x) < epsilon then velocity.x = 0
Each time I update the balls velocity and position? Is this what is generally done? Would it be reasonable to place that in my Vector classes setters for x and y? Or should I do it outside of my vector class when I'm calculating the velocities.
Also, what would be a reasonable epsilon value if I was using floats for my speed vector?
A reasonable value for epsilon is going to depend on the constraints of your system. If you are representing the ball graphically, then your epsilon might correspond to, say, a velocity of .1 pixels a second (ensuring that your notion of stopping matches the user's experience of the screen objects stopping). If you're doing a physics simulation, you'll want to tune it to the accuracy to which you're trying to measure your system.
As for how often you check - that depends as well. If you're simulating something in real time, the extra check might be costly, and you'll want to check every 10 updates or once per second or something. Or performance might not be an issue, and you can check with every update.
Instead of an epsilon for an IsStillMoving function, maybe you could use an UpdatePosition function, scheduled on an object-by-object basis based on its velocity.
I'd do something like this (in my own make-it-up-as-you-go pseudocode):
void UpdatePosition(Ball b) {
TimeStamp now = Clock.GetTime();
float secondsSinceLastUpdate = now.TimeSince(b.LastUpdate).InSeconds;
Point3D oldPosition = b.Position;
Point3D newPosition = CalculatePosition(b.Position, b.Velocity, interval);
b.MoveTo(newPosition);
float epsilonOfAccuracy = 0.5; // Accurate to one half-pixel
float pixelDistance = Camera.PixelDistance(oldPosition, newPosition);
float fps = System.CurrentFramesPerSecond;
float secondsToMoveOnePixel = (pixelDistance * secondsSinceLastUpdate) / fps;
float nextUpdateInterval = secondsToMoveOnePixel / epsilonOfAccuracy;
b.SetNextUpdateAt(now + nextUpdateInterval);
}
Balls moving very quickly would get updated on every frame. Balls moving more slowly might update every five or ten frames. And balls that have stopped (or nearly stopped) would update only very very rarely.
IMO your epsilon approach is fine. I would just experiment to see what looks or feels natural to the animation in the game.
Epsilon by nature is the smallest possible increment. Unfortunately, computers have different "minimal" increments of their own depending on the floating point representation. I would be very careful (and might even go higher than what I would calculate just for safety) playing around with that, especially if I want a code to be portable.
You may want to write a function that figures out the minimal increment on your floats rather than use a magic value.

Calculate the position of an accelerating body after a certain time [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
How do I calculate the position of an accelerating body (e.g. a car) after a certain time (e.g. 1 second)?
For a moving body that it not accelerating, it is a linear relationship, so I presume for an accelerating body it involves a square somewhere.
Any ideas?
The equation is: s = ut + (1/2)a t^2
where s is position, u is velocity at t=0, t is time and a is a constant acceleration.
For example, if a car starts off stationary, and accelerates for two seconds with an acceleration of 3m/s^2, it moves (1/2) * 3 * 2^2 = 6m
This equation comes from integrating analytically the equations stating that velocity is the rate-of-change of position, and acceleration is the rate-of-change of velocity.
Usually in a game-programming situation, one would use a slightly different formulation: at every frame, the variables for velocity and position are integrated not analytically, but numerically:
s = s + u * dt;
u = u + a * dt;
where dt is the length of a frame (measured using a timer: 1/60th second or so). This method has the advantage that the acceleration can vary in time.
Edit A couple of people have noted that the Euler method of numerical integration (as shown here), though the simplest to demonstrate with, has fairly poor accuracy. See Velocity Verlet (often used in games), and 4th order Runge Kutta (a 'standard' method for scientific applications) for improved algorithms.
Well, it depends on whether or not acceleration is constant. If it is it is simply
s = ut+1/2 at^2
If a is not constant, you need to numerically integrated. Now there is a variety of methods and none of them will beat doing this by hand for accuracy, as they are all ultimately approximate solutions.
The easiest and least accurate is Euler's method . Here you divide time into discrete chunks called time steps, and perform
v[n] = v[n-1] * t * a[t]
n is index, t is size of a time step. Position is similarly updated. This is only really good for those cases where accuracy is not all that important. A special version of Euler's method will yield an exact solution for projectile motion (see wiki), so while this method is crude, it can be perfect for some suituations.
The most common numerical integration method used in games and in some chemistry simulations is Velocity Verlet, which is a special form of the more generic Verlet method. I would recommend this one if Euler's is too crude.
In this article: http://www.ugrad.math.ubc.ca/coursedoc/math101/notes/applications/velocity.html (webarchive), you can find this formula:
p(t) = x(0) + v(0)*t + (1/2)at^2
where
p(t) = position at time t
x(0) = the position at time zero
v(0) = velocity at time zero (if you don't have a velocity, you can ignore this term)
a = the acceleration
t = your current itme
Assuming you're dealing with constant acceleration, the formula is:
distance = (initial_velocity * time) + (acceleration * time * time) / 2
where
distance is the distance traveled
initial_velocity is the initial velocity (zero if the body is intially at rest, so you can drop this term in that case)
time is the time
acceleration is the (constant) acceleration
Make sure to use the proper units when calculating, i.e. meters, seconds and so on.
A very good book on the topic is Physics for Game Developers.
Assuming constant acceleration and initial velocity v0,
x(t) = (1/2 * a * t^2) + (v0 * t)

Resources