I'm trying to create a projectile, which when fired will behave as if it was shoot from catapult. The problem is to calculate trajectory. I have starting position. Also target is the closest enemy.
I tried to implement this formula, which I found in 2d projectile trajectory?
xn = x0 + v * t * cos(theta)
yn = y0 + v * t * sin(theta)
And this is how I implemented it:
float v = 70f;
t += Gdx.graphics.getDeltaTime();
angle -= 0.1f;
float xn = originX + v* t * MathUtils.cosDeg(angle);
float yn = originY + v* t * MathUtils.sinDeg(angle);
position.set(x,y);
I'm trying to make projectile move along the trajectory line something like on video below, target is determined by the catapult, it's the closest enemy: https://www.youtube.com/watch?v=mwU24AuQibw
EDIT
private float g = 9.8f;
private float v = 50;
public void update()
{
t = Gdx.graphics.getDeltaTime();
float dx = originX - target.x;
float dy = originY - target.y;
double radi = Math.sqrt(Math.pow(v, 4) - g * (g * dx * dx + 2 * dy * v * v));
double theta1 = Math.atan((v*v + radi) / (g * dx));
double theta2 = Math.atan((v*v - radi) / (g * dx));
float xn = originX + v * t * MathUtils.cos((float) theta1);
float yn = originY + v * t * MathUtils.sin((float) theta2);
position.add(xn,yn);
I did the above code, but it makes the projectile to disappear, because I used add(xn,yn)
, but if I use set(xn, yn)
, projectile doesn't move at all. I was changing v trying different numbers, it doesn't make any difference. Also theta1 and theta2 gives me a NaN value.
FINAL EDIT
I tried all ways which I could think of, of implementing these formulas and it didn't work for me. I decided to make something different instead. Thank you all for the answers. I'll keep this thread so that someone may use the formulas posted here.