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
Related
I have written a program in C where I allocate memory to store a matrix of dimensions n-by-n and then feed a linear algebra subroutine with. I'm having big troubles in understanding how to identify time complexity for these operations from a plot. Particularly, I'm interested in identify how CPU time scales as a function of n, where n is my size.
To do so, I created an array of n = 2, 4, 8, ..., 512 and I computed the CPU time for both the operations. I repeated this process 10000 times for each n and I took the mean eventually. I therefore come up with a second array that I can match with my array of n.
I've been suggested to print in double logarithmic plot, and I read here and here that, using this way, "powers shows up as a straight line" (2). This is the resulting figure (dgesv is the linear algebra subroutine I used).
Now, I'm guessing that my time complexity is O(log n) since I get straight lines for both my operations (I do not take into consideration the red line). I saw the shapes differences between, say, linear complexity, logarithmic complexity etc. But I still have doubts if I should say something about the time complexity of dgesv, for instance. I'm sure there's a way that I don't know at all, so I'd be glad if someone could help me in understanding how to look at this plot properly.
PS: if there's a specific community where to post this question, please let me know so I could move it avoiding much more mess here. Thanks everyone.
Take your yellow line, it appears to be going from (0.9, -2.6) to (2.7, 1.6), giving it a slope roughly equal to 2.5. As you're plotting log(t) versus log(n) this means that:
log(t) = 2.5 log(n) + c
or, exponentiating both sides:
t = exp(2.5 log(n) + c) = c' n^2.5
The power of 2.5 may be an underestimate as your dsegv likely has a cost of 2/3 n^3 (though O(n^2.5) is theoretically possible).
Hi,
I have a big difficult trying to understand why in the equation of the hyperplane of support vector machine there is a 1 after >=?? w.x + b >= 1 <==(why this 1??) I know that could be something about the intersection point on y axes but I cannot relate that to the support vector and to its meaning of classification.
Can anyone please explain me why the equation has that 1(-1) ?
Thank you.
The 1 is just an algebraic simplification, which comes in handy in the later optimization.
First, notice, that all three hyperplanes can be denotes as
w'x+b= 0
w'x+b=+A
w'x+b=-A
If we would fix the norm of the normal w, ||w||=1, then the above would have one solution with some arbitrary A depending on the data, lets call our solution v and c (values of optimal w and b respectively). But if we let w to have any norm, then we can easily see, that if we put
w'x+b= 0
w'x+b=+1
w'x+b=-1
then there is one unique w which satisfies these equations, and it is given by w=v/A, b=c/A, because
(v/A)'x+(b/A)= 0 (when v'x+b=0) // for the middle hyperplane
(v/A)'x+(b/A)=+1 (when v'x+b=+A) // for the positive hyperplane
(v/A)'x+(b/A)=-1 (when v'x+b=-A) // for the negative hyperplane
In other words - we assume that these "supporting vectors" satisfy w'x+b=+/-1 equation for future simplification, and we can do it, because for any solution satisfing v'x+c=+/-A there is a solution for our equation (with different norm of w)
So once we have these simplifications our optimization problem simplifies to the minimization of the norm of ||w|| (maximization of the size of the margin, which now can be expressed as `2/||w||). If we would stay with the "normal" equation with (not fixed!) A value, then the maximization of the margin would be in one more "dimension" - we would have to look through w,b,A to find the triple which maximizes it (as the "restrictions" would be in the form of y(w'x+b)>A). Now, we just search through w and b (and in the dual formulation - just through alpha but this is the whole new story).
This step is not required. You can build SVM without it, but this makes thing simplier - the Ockham's razor rule.
This boundary is called "margin" and must be maximized then you have to minimize ||w||.
The aim of SVM is to find a hyperplane able to maximize the distances between the two groups.
However there are infinite solutions ( see figure: move the optimal hyperplane along the perpendicualr vector) and we need to fix at least the boundaries: the +1 or -1 is a common convention to avoid these infinite solutions.
Formally you have to optimize r ||w|| and we set a bounadry condition r ||w|| = 1.
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.
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)
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.