I am using gravity in a 2d environment for my game. The objects I use in my game all have x and y coordinates, they can be "thrown" into a level, meaning instantiated, then given a specific origin location and then given new coordinates each frame with the following gravity:
public void throwObject(float delta) {
setX(getX() + velocity.x * delta);
setY(getY() + velocity.y * delta);
velocity.y += gravity.y * delta;
}
with the following:
Vector2 GRAVITY = new Vector2(0, -10);
From a given originx and originy, the objects "move" accordingly, this works well.
Now I would like to make the objects move to a a given destination, for example at:
destinationx = 50;
destinationy = 350;
If I use a static origin x and originy, how can I calculate velocity.x and velocity.y so that the object is thrown with a projectile curve to the specified destination coordinates?
Edit: I have made some progress determining the calculation for velocity.x:
velocity.x = (destinationx - originx) / 100;
where 100 is the number of frames I have set as static. This works well.
For velocity.y, I have tried:
velocity.y = (destinationy - originy) / 100 * delta + Math.sqrt(gravity) * 2;
it gives a result that looks close from the right formula, but not exactly it
First of all: There are infinitely many solutions. Including the "trivial" one, where the velocity is just the difference of the source and the target position, divided by "delta" (that is, the solution where the target would be reached in a single step, due to the velocity being "infinitely high").
But one intuitively can imagine what you want to achieve, so I'll stop nitpicking:
You want to specify the velocity in cartesian coordinates: (deltaX, deltaY). It is more convenient to think of this velocity in terms of polar coordinates: (angle, power), where "power" represents the magnitude of the initial velocity. (For conversion rules, see Wikipedia: Polar coordinate system).
Given a fixed initial velocity, there are either zero, one or two angles where the projectile will hit the target. Given a fixed initial angle, there may either be zero or one initial velocity where the projectile will hit the target. But if you can choose both, the velocity and the angle, then there is an infinite number of ballistic trajectories starting at the origin and passing through the target.
I slightly extended a Projectile Shooter example from one of my previous answers, using some of the formulas from wikipedia, mainly from Wikipedia: Trajectory of a projectile:
You can use the sliders to change the angle and the power, and use the mouse to drag the origin and the target. The text contains two important outputs:
NaN
.NaN
.Depending on the degrees of freedom that you would like for your velocity, you may probably extract the relevant formulas. (Apologies for the missing comments, this "SSCCE" (Short, Self Contained, Compilable, Example) has gradually turned into a "LSCCE"...)