Original Post
Hi, please help! This is driving me crazy.
I have a cannon and a target. I want to make the cannon shoot at the target tanking into account gravity. The only thing I need to know is the cannon's angle since the initial velocity is fixed.
The problem I have is that atan returns the wrong angles. It seems to be a quadrant problem since atan only returns angles between -PI/2 and PI/2.
The coordinates system has the y axis flipped so -y is up.
The angles are measured clockwise from the -y axis so:
(1) vx = v * -cos(angle)
(2) vy = v * sin(angle)
using the equations of motion:
(3) pfy = p0y + vy * t + 0.5 * g * t^2
(4) pfx = p0x + vx * t
where g is gravity, t is time, p0x and p0y are the position of the cannon and pfx and pfy is the position of the target.
from (4) you get:
(5) t = (pfx - p0x) / vx
Now substituting (1), (2) and (5) in (3) you get a quadratic equation were x = cot(angle) and coefficients a, b and c are as follows:
a = g * (pfx - p0x)^2 / (2 * v * v)
b = -(pfx - p0x)
c = (p0y - pfy) + g * (pfx - p0x)^2 / (2 * v * v)
Then, I find x with the solution to a quadratic equation
(-b +- sqrt(b*b - 4*a*c)) / 2*a
since x = cot(angle) = 1/tan(angle) the angle is found with Math.atan(1/x).
I'm getting weird quadrant problems. The cannon sometimes aims correctly and sometimes it just fires the opposite way.
Does anybody have any idea of what I'm doing wrong?
Thanks in advance.
SP.
Similar problem found in this topic:
http://www.gamedev.net/community/forums/topic.asp?topic_id=560312
I have a cannon and a target. I want to make the cannon shoot at the target tanking into account gravity. The only thing I need to know is the cannon's angle since the initial velocity is fixed.
The problem I have is that atan returns the wrong angles. It seems to be a quadrant problem since atan only returns angles between -PI/2 and PI/2.
The coordinates system has the y axis flipped so -y is up.
The angles are measured clockwise from the -y axis so:
(1) vx = v * -cos(angle)
(2) vy = v * sin(angle)
using the equations of motion:
(3) pfy = p0y + vy * t + 0.5 * g * t^2
(4) pfx = p0x + vx * t
where g is gravity, t is time, p0x and p0y are the position of the cannon and pfx and pfy is the position of the target.
from (4) you get:
(5) t = (pfx - p0x) / vx
Now substituting (1), (2) and (5) in (3) you get a quadratic equation were x = cot(angle) and coefficients a, b and c are as follows:
a = g * (pfx - p0x)^2 / (2 * v * v)
b = -(pfx - p0x)
c = (p0y - pfy) + g * (pfx - p0x)^2 / (2 * v * v)
Then, I find x with the solution to a quadratic equation
(-b +- sqrt(b*b - 4*a*c)) / 2*a
since x = cot(angle) = 1/tan(angle) the angle is found with Math.atan(1/x).
I'm getting weird quadrant problems. The cannon sometimes aims correctly and sometimes it just fires the opposite way.
Does anybody have any idea of what I'm doing wrong?
Thanks in advance.
SP.
Similar problem found in this topic:
http://www.gamedev.net/community/forums/topic.asp?topic_id=560312