Most effective way to handle velocity - physics

Basically, I am curious if xVel and yVel variables would work the best, or if I should use a velocity and a direction variable.
Also, this is how it would be handled on update: (psuedocode)
For xVel and yVel :
x += xVel;
y += yVel;
For velocity and direction :
x += velocity * (cos(direction));
y += velocity * (sin(direction));
Note: I am not sure if the second one will work properly. I do not have trigonometry skills.
So, is the first way more effective, or the second? And am I doing the second one completely wrong?

It depends on your application. You can use an arctangent function to find the theta from any given moment, of course. However, if your have graphics which will rotate with the angle of the object, then you may want to stick to polar.
Basically, the rule of thumb I use is this: If you're dealing with X and Y accelerations as well as velocities, then you want to stick to rectangular coordinates and use delta-x and delta-y variables. If you want to handle object rotation, and the angle is computed upon regularly, then you may want to use polar.
It depends on the application.

Both ways are equally effective, since they should give the same answer. However I would add an extra numerical-time-step term to make it a better numerical "simulation":
x += xVel * timeStep;
y += yVel * timeStep;
Or
x += totalVel * cos(direction) * timeStep;
y += totalVel * sin(direction) * timeStep;
Both ways would give the same results, however the calculation time will probably diverge. If the amount of calculations for one method would be much more than the other it will be very likely that the other one will be faster. But if you are unsure you could always run a test script in which you test each method quite a few times and track the amount of time the CPU needed to perform them.

Related

Using AMPL find the largest rectangle in a circle

So this is a pretty simple problem, given a circle of diameter 60 units, find the largest rectangle that fits in it. Using some pretty simple maths we know it'll have an area of 1800 units.
So I created this AMPL model
param diameter := 60;
param radius := diameter / 2;
var tlX; # top left x of the rectangle
var tlY; # top left y of the rectangle
subject to tlInside: sqrt(tlX*tlX + tlY*tlY) < radius; # make sure its inside the circle
var brX; # bottom right x of the rect
var brY; # bottom right y of the rectangle
subject to brInside: sqrt(brX*brX + brY*brY) <= radius; # make sure its inside the circle
var xDiff = brX - tlX;
var yDiff = brY - tlY;
maximize Area: xDiff * yDiff;
First up:
option solver gurobi; solves it, but creates an area of 0. lol, wut?
Second up:
option solver HiGHS; solves it, but creates an area of 12.3873. Closer. But still not clearly near optimal
Third up:
option solver cbc; solves it, but create an area of 1820.51. This is close to the optimal (1800) but it generates the variables that violate the constraints!
All other solvers I tried couldn't even come up with a solution.
So what's going on. Seems like it's a pretty trivial problem?
You have to realize that as you model the problem you are creating a non-convex objective function over a convex set of feasible points. That is far from trivial to optimize, and any locally optimal solution may be returned as optimal. I guess this is what happens with gurobi and HiGHS.

Physics - Projectile get launch angle to hit desired location?

I am programming a simple ball projectile in a game.
the update pretty much looks like:
velocity += gravity;
velocity *=0.9;
pos += vel;
Is there a way to set the angle and power of the launch in order to hit a point that is specified with the mouse?
like peggle, http://youtu.be/4KbNiWsgJck?t=45s
I know there is a solution that I have used several years ago, but I can't find it.
I believed it turned my update into a quadratic formula, or derived it or something.
It had two solutions that was solved with the quadratic equation.
ps- hopefully this could be in 3D, but I could use a 2D solution too because my curve would be 2D
any help?
thanks,
Dan
Yes, you can do this. If you can change the angle and speed, you have more variability than you need, so you have to find a reasonable set of parameters that will work, which isn't hard. The basic equations are:
x = x0 + t*v0x
y = y0 + v0yt + (1/2)ayt2
Here, x and y will be the points you want to hit, and t will be the time that you hit them. t won't show up in the final solution, but you'll use it as in intermediary to calculate the values you want.
Basically, then, pick a reasonable value for v0x. Using the x-equation, find what t will be when the target is hit. Then plug this value into the y-equation, and solve for v0y. This then will give you a pair of values of v0x and v0y that will work to hit the target.

how to make a test if the ball reached the hole?

I am making really simple app in xcode.
And I want to make, if the ball reach the hole the game should finish
So i tried to make.
if (ball . center == hole.center )
and another ways and I failed
and I also tried this
(ball.frame.origin.x == hole.frame.origin.x && ball.frame.origin.y == hole.frame.origin.y)
And as usual failed
Please help.
i just want if the fram of the ball touches the hole The Game FINISH
Problem is that you shouldn't check for a position to be exactly the same, that's not how it works with floating point coordinates (which I guess you are using) and precision of movement of things in games which cannot require to have object on same indentical position.
You should rather check if distance is less than a threshold:
float bx = ball.frame.origin.x;
float by = ball.frame.origin.y;
float hx = hole.frame.origin.x;
float hy = hole.frame.origin.y;
// you don't actually need abs since you are going to raise to the power of 2
// but for sake of soundness it makes sense
float dx = abs(bx-hx);
float dy = abs(by-hy);
if (sqrt(dx*dx + dy*dy) < THRESHOLD) {
// the ball is enough near to center
}
You could use CGRectIntersectsRect (more on CGGeometry) to see if the ball and hole intersect eachother:
if (CGRectIntersectsRect(ball.frame, hole.frame)) {
// Goal reached!
}
... or CGRectEqualToRect the same way (if you want to check if the frames are exactly the same).
My guess would be that you do not want to test whether the two centers are equal, but whether they are close enough to eachother. For example less then epsilon away in the x and y direction.

formulas in Projectile Motion?

how can i calculate angle to reach particular height?
suppose i want height 320.time is increasing as 0.1.
i am using h = (u sin(angle))^2 / 2g;
where can i put the time?
The inverse of the sin() function is called the arcsine, or sin-1 in mathematical notation. In many programming languages, it's available as asin().
From my answer to your previous question:
Where y is the height you want to reach (320 in this case), and assuming you're starting at y=0:
angle = arctan( 2*y / x )
where x is the distance on the X-AXIS between your starting point and the point where you want to reach that height, which is necessary in order to specify an angle.
If you really want me to, I can derive this one for you, but it follows directly from my answer to your previous question.
Also (since I can't comment answers yet I'm saying this here), you may be having issues getting an angle "less than 1" because you're trying to use degrees instead of radians. Many math libraries work in radians, so convert your angles.

Normal Distribution function

edit
So based on the answers so far (thanks for taking your time) I'm getting the sense that I'm probably NOT looking for a Normal Distribution function. Perhaps I'll try to re-describe what I'm looking to do.
Lets say I have an object that returns a number of 0 to 10. And that number controls "speed". However instead of 10 being the top speed, I need 5 to be the top speed, and anything lower or higher would slow down accordingly. (with easing, thus the bell curve)
I hope that's clearer ;/
-original question
These are the times I wish I remembered something from math class.
I'm trying to figure out how to write a function in obj-C where I define the boundries, ex (0 - 10) and then if x = foo y = ? .... where x runs something like 0,1,2,3,4,5,6,7,8,9,10 and y runs 0,1,2,3,4,5,4,3,2,1,0 but only on a curve
Something like the attached image.
I tried googling for Normal Distribution but its way over my head. I was hoping to find some site that lists some useful algorithms like these but wasn't very successful.
So can anyone help me out here ? And if there is some good sites which shows useful mathematical functions, I'd love to check them out.
TIA!!!
-added
I'm not looking for a random number, I'm looking for.. ex: if x=0 y should be 0, if x=5 y should be 5, if x=10 y should be 0.... and all those other not so obvious in between numbers
alt text http://dizy.cc/slider.gif
Okay, your edit really clarifies things. You're not looking for anything to do with the normal distribution, just a nice smooth little ramp function. The one Paul provides will do nicely, but is tricky to modify for other values. It can be made a little more flexible (my code examples are in Python, which should be very easy to translate to any other language):
def quarticRamp(x, b=10, peak=5):
if not 0 <= x <= b:
raise ValueError #or return 0
return peak*x*x*(x-b)*(x-b)*16/(b*b*b*b)
Parameter b is the upper bound for the region you want to have a slope on (10, in your example), and peak is how high you want it to go (5, in the example).
Personally I like a quadratic spline approach, which is marginally cheaper computationally and has a different curve to it (this curve is really nice to use in a couple of special applications that don't happen to matter at all for you):
def quadraticSplineRamp(x, a=0, b=10, peak=5):
if not a <= x <= b:
raise ValueError #or return 0
if x > (b+a)/2:
x = a + b - x
z = 2*(x-a)/b
if z > 0.5:
return peak * (1 - 2*(z-1)*(z-1))
else:
return peak * (2*z*z)
This is similar to the other function, but takes a lower bound a (0 in your example). The logic is a little more complex because it's a somewhat-optimized implementation of a piecewise function.
The two curves have slightly different shapes; you probably don't care what the exact shape is, and so could pick either. There are an infinite number of ramp functions meeting your criteria; these are two simple ones, but they can get as baroque as you want.
The thing you want to plot is the probability density function (pdf) of the normal distribution. You can find it on the mighty Wikipedia.
Luckily, the pdf for a normal distribution is not difficult to implement - some of the other related functions are considerably worse because they require the error function.
To get a plot like you showed, you want a mean of 5 and a standard deviation of about 1.5. The median is obviously the centre, and figuring out an appropriate standard deviation given the left & right boundaries isn't particularly difficult.
A function to calculate the y value of the pdf given the x coordinate, standard deviation and mean might look something like:
double normal_pdf(double x, double mean, double std_dev) {
return( 1.0/(sqrt(2*PI)*std_dev) *
exp(-(x-mean)*(x-mean)/(2*std_dev*std_dev)) );
}
A normal distribution is never equal to 0.
Please make sure that what you want to plot is indeed a
normal distribution.
If you're only looking for this bell shape (with the tangent and everything)
you can use the following formula:
x^2*(x-10)^2 for x between 0 and 10
0 elsewhere
(Divide by 125 if you need to have your peek on 5.)
double bell(double x) {
if ((x < 10) && (x>0))
return x*x*(x-10.)*(x-10.)/125.;
else
return 0.;
}
Well, there's good old Wikipedia, of course. And Mathworld.
What you want is a random number generator for "generating normally distributed random deviates". Since Objective C can call regular C libraries, you either need a C-callable library like the GNU Scientific Library, or for this, you can write it yourself following the description here.
Try simulating rolls of dice by generating random numbers between 1 and 6. If you add up the rolls from 5 independent dice rolls, you'll get a surprisingly good approximation to the normal distribution. You can roll more dice if you'd like and you'll get a better approximation.
Here's an article that explains why this works. It's probably more mathematical detail than you want, but you could show it to someone to justify your approach.
If what you want is the value of the probability density function, p(x), of a normal (Gaussian) distribution of mean mu and standard deviation sigma at x, the formula is
p(x) = exp( ((x-mu)^2)/(2*sigma^2) ) / (sigma * 2 * sqrt(pi))
where pi is the area of a circle divided by the square of its radius (approximately 3.14159...). Using the C standard library math.h, this is:
#include <math>
double normal_pdf(double x, double mu, double sigma) {
double n = sigma * 2 * sqrt(M_PI); //normalization factor
p = exp( -pow(x-mu, 2) / (2 * pow(sigma, 2)) ); // unnormalized pdf
return p / n;
}
Of course, you can do the same in Objective-C.
For reference, see the Wikipedia or MathWorld articles.
It sounds like you want to write a function that yields a curve of a specific shape. Something like y = f(x), for x in [0:10]. You have a constraint on the max value of y, and a general idea of what you want the curve to look like (somewhat bell-shaped, y=0 at the edges of the x range, y=5 when x=5). So roughly, you would call your function iteratively with the x range, with a step that gives you enough points to make your curve look nice.
So you really don't need random numbers, and this has nothing to do with probability unless you want it to (as in, you want your curve to look like a the outline of a normal distribution or something along those lines).
If you have a clear idea of what function will yield your desired curve, the code is trivial - a function to compute f(x) and a for loop to call it the desired number of times for the desired values of x. Plot the x,y pairs and you're done. So that's your algorithm - call a function in a for loop.
The contents of the routine implementing the function will depend on the specifics of what you want the curve to look like. If you need help on functions that might return a curve resembling your sample, I would direct you to the reading material in the other answers. :) However, I suspect that this is actually an assignment of some sort, and that you have been given a function already. If you are actually doing this on your own to learn, then I again echo the other reading suggestions.
y=-1*abs(x-5)+5