Reputation: 33
So I am making a 2D android game where you aim with your cursor and your character shoots where your cursor clicks. When the arrow is created this method is called
private final float GRAVITY = 100, SPEED = 50f;
public Arrow(float dx, float dy, float x1, float y1, float x2, float y2,)
{
destination = new Vector2(dx, dy);//mouse clicked here
//x1 and y1 are the starting coordinates
bounds = new Polyline(new float[]{x1, y1, x2, y2});
double r = Math.atan2(dy-y1, dx-x1);//calculate angle
velocity = new Vector2();
velocity.x = (float)(Math.cos(r) * SPEED);
velocity.y = (float)(Math.sin(r) * SPEED) + ACCOUNT FOR GRAVITY;
acceleration= new Vector2(0, GRAVITY);
}
and this is the update method, pretty straight forward
public void update(float delta)
{
velocity.add(acceleration.cpy().scl(delta));
position.add(velocity.cpy().scl(delta));
}
How do I account for gravity? If gravity is set to 0 the arrow travels in a straight line to the coordinates the mouse clicked, but with gravity it always falls short. Im not sure how to account for gravity. I think delta might be screwing me up.
Upvotes: 0
Views: 185
Reputation: 484
This is more of a math / physics question than a programming question. So first of all, you know the horizontal velocity of the arrow is constant (unless you have air resistance, in which case it is a lot more complicated). You can calculate the time it will take for the arrow to reach it's destination's x coordinate.
let (dx, dy) = displacement from launcher to destination
let c = cos(angle), s = sin(angle), vx = c * speed, vy = s * speed
vx * t = dx
t = dx / vx
With this value, you can compute the vertical displacement
dy = 0.5*acc * t^2 + V0 * t
dy = 0.5*acc * (dx/vx)^2 + vy*t
dy = 0.5*acc * (dx/(c*speed))^2 + (s*speed)*(dx/(c*speed))
since sin = sqrt(1 - cosine^2),
dy = 0.5*acc * (dx/(c*speed))^2 + (sqrt(1-c^2)*speed)*(dx/c*speed))
Now you have an equation with only known values (acc, dy, dx, speed) and c. If you solve for c, you know the cosine and you can find the sin.
Upvotes: 2