how to get trajectory of an object1 when we swipe an object2? - cocoa-touch

I am writing an game app in iPad using cocos2d. And the game is in landscape mode. It have a sprite gun that shoots, and the sprite is the middle (512,10).
The targets appear along the x-axis. By swiping on the sprite gun I have to generate a trajectory of the bullet according to the angle I have swiped.
So, I have initial and final coordinates of touch of gun. And the angle. How can I get the trajectory ?
Thank You.

Assuming the ground is flat, no air resistance, and the bullet is fired at coordinates (0, 0), the formula for height as a function of distance travelled along the ground is as follows:
a = launch angle
v = launch speed
x = distance travelled along the ground
y = distance above the ground
g = acceleration due to gravity.
y(x) = (x * tan(a)) - ( ( (g / ( cos(a) * cos(a) ) ) / (2 * v * v) ) * (x * x) )
Check what units your maths/trigonometry library uses for angles (degrees or radians)
So, assuming the bullet is moving in +ve x direction, plot (0, y(0)), (1, y(1)), (2, y(2)) etc. until y(x) is < 0, meaning that the bullet has hit the ground.
(Don't forget to add 512 to x, and 10 to y when plotting, to match the start point at your gun sprite position).
Here endeth the maths lesson. Over to you on the iPad code.
If you want to get really fancy, the Wikipedia Trajectory page is fairly thorough.

Related

How can I implement degrees round the drawn compass

I am developing a GPS waypoint application. I have started by drawing my compass but am finding it difficult to implement degree text around the circle. Can anyone help me with a solution? The compass image am working on] 1 here shows the circle of the compass I have drawn.
This image here shows what I want to achieve, that is implementing degree text round the compass [Image of what I want to achieve] 2
Assuming you're doing this in a custom view, you need to use one of the drawText methods on the Canvas passed in to onDraw.
You'll have to do a little trigonometry to get the x, y position of the text - basically if there's a circle with radius r you're placing the text origins on (i.e. how far out from the centre they are), and you're placing one at angle θ:
x = r * cosθ
y = r * sinθ
The sin and cos functions take a value in radians, so you'll have to convert that if you're using degrees:
val radians = (degrees.toDouble() / 360.0) * (2.0 * Math.PI)
and 0 degrees is at 3 o'clock on the circle, not 12, so you'll have to subtract 90 degrees from your usual compass positions (e.g. 90 degrees on the compass is 0 degrees in the local coordinates). The negative values you get are fine, -90 is the same as 270. If you're trying to replicate the image you posted (where the numbers and everything else are rotating while the needle stays at the top) you'll have to apply an angle offset anyway!
These x and y values are distance from the centre of the circle, which probably needs to be the centre of your view (which you've probably already calculated to draw your circle). You'll also need to account for the extra space you need to draw those labels, scaling everything so it all fits in the View

Relation between horizontal, vertical and diagonal Field-of-View

Is there a mathematical relation between those values? If I know hFOV and vFOV can I calculate the diagonal FOV without involving other values like focal lengths etc?
My first thought was to use Pythagorean theorem but maybe it's wrong.
The physical quantities of interest are the sensor size and the focal length. The latter, in the pinhole camera model, is the the distance between the camera center and the image plane. Therefore, if you denote with f the focal length (in mm), W and H respectively the image sensor width and height (in mm), and assume the focal axis is orthogonal to the image plane, by simple trigonometry it is:
FOV_Horizontal = 2 * atan(W/2/f) = 2 * atan2(W/2, f) radians
FOV_Vertical = 2 * atan(H/2/f) = 2 * atan2(H/2, f) radians
FOV_Diagonal = 2 * atan2(sqrt(W^2 + H^2)/2, f) radians
Note that, if you have the sensor size and horizontal or vertical fov's, you can solve one of the first two equations for f and plug it into the third one to get the diagonal fov.
When, as is usual, the focal length is estimated through camera calibration, and is expressed in pixels, the above expressions need some adapting.
Denote with K the 3x3 camera matrix, with the camera frame having its origin at the camera center (focal point), X axis oriented left-to-right, Y axis top-to-bottom and Z axis toward the scene. Let Wp and Hp respectively be the width and height of the image in pixels.
In the simplest case the focal axis is orthogonal to the image plane (K12 = 0), the pixels are square (K11 = K22), and the principal point is at the image center (K13 = Wp/2; K23 = Hp/2). Then the same equations as above apply, replacing W with Wp, H with Hp and f with K11.
A lil more complex is the case just as above, but with the principal point off-center. Then one simply adds the two sides of each FOV angle. So, for example:
FOV_Horizontal = atan2(Wp/2 - K13, K11) + atan2(Wp/2 + K13, K11)
If the pixels are not square the same expressions apply for FOV_vertical, but using K22 and Hp, etc. The diagonal is a tad trickier, since you need to "convert" the image height into the same units as the width. Use the "pixel aspect ratio" PAR=K22/K11 for this purpose, so that:
FOV_Diagonal = 2 * atan2(sqrt(Wp^2 + (Hp/PAR)^2) / 2, K11)

Random movement using physics, CGPoint, vectors, a little confused on the physics/math side of things

I've managed to get Chipmunk physics and some other stuff to lay down a ball on my screen, and I can affect the gravity with some buttons / accelerometer. Yay me!
Next up, I'd like to turn off the gravity, and simulate a top-down view, where that ball moves around the screen of its own volition. I can apply forces to the ball using body -> f = cpv(dx, dy), but I'm not quite up on my physics and mathematics, so I'm trying to understand how the two values I feed it cause the movement.
I understand that positive values will move it right or down, and negative values will move it left or up, but that's about all I'm understanding at this point.
If I wanted to, say, pick a random compass bearing (0 - 359 degrees) and move it on that bearing, how would such a value translate into a vector?
I've created this method, but it's not working as expected and I'm unsure what I'm doing wrong:
- (CGPoint) getVectorFromAngle: (float) angle AndMagnitude: (float) magnitude
{
float x = magnitude * cos(angle);
float y = magnitude * sin(angle);
CGPoint point = CGPointMake(x, y);
NSLog(#"Made a CGPoint of X: %f and Y: %f.", point.x, point.y);
return point;
}
If I feed it an angle of 45 and a magnitude of 10, it creates X as 5.253220 and 8.509035. However, the calculator found here shows that it should create X and Y as 7.0711.
What do I have wrong here?
sin and cos take angles in radians, multiply your angles by π/180.
It's also good to point out that Chipmunk already contains a functions that do exactly what you want.
cpvmult(cpvforangle(radians), magnitude)

How to simulate Mouse Acceleration?

I've written iPhone - Mac, Client - Server app that allows to use mouse via touchpad.
Now on every packet sent I move cursor by pecific amount of pixels (now 10px).
It isn't accurate. When i change sensitivity to 1px it's to slow.
I am wondering how to enhance usability and simulate mouse acceleration.
Any ideas?
I suggest the following procedure:
ON THE IPHONE:
Determine the distance moved in x and y direction, let's name this dx and dy.
Calculate the total distance this corresponds to: dr = sqrt(dx^2+dy^2).
Determine how much time has passed, and calculate the speed of the movement: v = dr/dt.
Perform some non-linear transform on the velocity, e.g.: v_new = a * v + b * v^2 (start with a=1 and b=0 for no acceleration, and then experiment for optimal values)
Calculate a new distance: dr_new = v_new * dt.
Calculate new distances in x/y direction:
dx_new = dx * dr_new / dr and dy_new = dy * dr_new / dr.
Send dx_new and dy_new to the Mac.
ON THE MAC:
Move the mouse by dx_new and dy_new pixels in x/y direction.
NOTE: This might jitter a lot, you can try averaging the velocity after step (3) with the previous two or three measured velocities if it jitters to much.

Vertical circular motion : time(x/y) versus velocity equation

I wanted to simulate the following through animation :
A ball starts with a certain velocity at the bottom most point of
a vertical circular loop and keeps rolling in it until its velocity permits.
For this, I wanted to find velocity/x/y vs. time equation.
For e.g. if the ball had mass : 5Kg, radius of the circular loop = 10m,
and initial velocity of the ball is 200 m/s, what will its velocity and (x,y) position
be after 5 seconds?
thanks.
Sliding, frictionless case with a point-particle ball
In this case we aren't worrying about rotational energy and are assuming that the ball is actually a point particle. Then, in order for the ball to stay on at the top, the centripetal force condition has to be satisfied:
m * v_top^2 / r = m * g
so
v_top = sqrt(r * g)
So the minimum initial velocity is determined by:
1 / 2 * m * v0^2 >= 1 / 2 * m * v_top^2 + m * g * 2 * r
v0 >= sqrt(5 * r * g)
This is similar to what Pete said, except that he forgot the centripetal force condition to stay on at the top.
Next, the acceleration tangential to the track is given by:
a = - g * sin(theta)
but a = r * alpha = r * d^2(theta)/dt^2 where alpha is the rotational acceleration. Thus, we get
r * d^2(theta)/dt^2 = g * sin(theta)
However, I don't know of an analytical solution to this differential equation and Mathematica was stumbling with finding one too. You can't just move the dts to the other side and integrate because theta is a function of t. I would recommend solving it by numerical means such as a Runga-Kutte or maybe the Verlet method. I solved it using Mathematica for the parameters you gave, but with the ball moving so quickly, it doesn't really slow down much in going around. When I lowered the initial velocity though, I was able to see the speeding up and slowing down by plotting theta as a function of time.
Adding in other things like a finite ball radius, rotational energy and friction are certainly doable, but I would worry about being able to solve this first case before moving on because it only gets more complicated from here. By the way, with the friction you will have to choose some kinetic coefficient of friction for your given materials which will of course be proportional to the normal force exerted on the ball by the track which can be solved for by summing the force components along the radius of the circle and don't forget to include the centripetal force condition.
If you haven't done this sort of physics before, I definitely recommend getting a introductory good book on physics (with calculus) and working through it. You only need to bother with the sections that apply to mechanics though that is a very large section of the book probably. There might be better routes to pursue though like some of the resources in this question.
If there are no acceleration (x,y) =(xstart+ vx*time ,ystart + vy*time) and speed remain the same, and it is not related to the radius
Since the velocity is constant you will have an angular velocity of omega = vel / radius. You will obtain how many radians you ball will move per second over its circular path.
To get the position at time t you just have to exploit polar coordinates:
x = x_center + sin( 3/2*PI + omega*t)*radius
y = y_center + cos( 3/2*PI + omega*t)*radius
This because you start from bottom point of the circle (so its 3/2*PI) plus how many radiants you move every second (we obtained it from tangential velocity). All multiplied for the radius, otherwise you will consider a unity circle.
EDIT: Since you wonder how to find a position of an object that is subject to many different forces I can tell you that usually a physical engine doesn't care about finding equations of moving objects. It just applies forces to objects considering their intended motions (like your circular one) or environmental factors (like gravity or friction) and calculates coordinates step by step by applying forces and using an integrator to see the results.
Ignoring friction, the forces on the ball are gravity and the track.
First, there are two main cases - is the velocity enough for the ball to loop-the-loop or not:
initial energy = 1/2 m v² = 0.5 * 5 * 200 * 200
potential energy = m g h = 5 * 9.8 * 20
so it will go round the whole loop.
Initially the ball is at the bottom of the loop, theta = 0
The acceleration on the ball is the component of g along the track
a = g⋅sin theta
The distance travelled is theta * radius. It is also the double integral of acceleration against time.
theta ⋅ radius = double integral of acceleration against time
Integrating acceleration once gives velocity, integrating velocity gives distance.
so solve this for t:
theta ⋅ r = ∫(∫ g⋅sin theta.dt).dt
then your x and y are trivial functions of theta.
Whether you solve it analytically or numerically is up to you.
With dynamic friction, friction is usually proportional to the normal force on the bodies. So this will equal the centripetal force - proportional to the square of the angular velocity, and the component of gravity normal to the track (g sin theta)
You didn't tell anything about how you want your velocity to change. Do you have any friction model? If there is no friction, then the formulas are simple:
length = velocity*t
x = sin(length)*radius
y = -cos(length)*radius
If the velocity is changing, then you have to change length to something like
length = integral over dt[0..t] (velocity dt)
The only thing I wanted to add is the if this is real ball (sphere) with mass 5kg then it must have a diameter dia=(6*m/(PI*rho))^(1/3) where rho is the density of the material. For steel (rho=7680) the diameter is dia=0.1075 meters. Therefore the pitch radius (radius at which the center of gravity of the ball rides on) is equal to R=10-(dia/2) or R=9.9466 meters.
The problem gets a little more complex when friction is included. For one you have to consider the direction of friction (assuming dry friction theory). That depends on the amount the ball rotates in its axis and that depends on moment of inertia of the ball.
When you do the simulation you might want to monitor the total kinetic energy + the total potential energy and make sure your are not adding energy to the system (or taking away). [Don't forget to include the rotational component for the kinetic energy]
Get a standard book on dynamics, and I am sure a similar problem is already described in the book.I would recommend "Vector Mechanic for Engineers - Dynamics".