- Home /
Calculating ballistic angle to a target
I'm writing a custom BallisticArc class for... well, dealing with ballistic arcs but I'm running into a snag: one of the constructors takes in a target and a velocity, then calculates the angle to reach it, based off the equation on these two pages:
Which I have implemented as follows:
public BallsiticArc(Vector2 start, Vector2 target, float velocity){
float v = velocity;
float v2 = v*v;
this.start = start;
g = Mathf.Abs(Physics.gravity.y);
float x = target.x - start.x;
flipped = !Sign(x); //returns a bool based on the sign: returns value >= 0
//this is just for cases where we are aiming 'behind' us
if(flipped) x = -x; //ensure a positive x value for calculations
float y = target.y - start.y;
angle = Mathf.Atan((v2 + Mathf.Sqrt(v2*v2 - g*(g*x*x + 2*y*v2))) / g*x);
Debug.Log("X: " + x + ", Y: " + y + ", angle: " + angle * Mathf.Rad2Deg);
sinA = Mathf.Sin(angle);
cosA = Mathf.Cos(angle);
_valid = true;
launchVelocity = new Vector2(v * cosA, v * sinA);
}
However, I'm getting completely inaccurate results; the angle drops only when x is extremely close; when x is further away the angle climbs to 90:
I've checked over the equation obsessively in case I got a bracket wrong, and I've tried the alternate form ('v2 - ...' instead of 'v2 + ...') but it just gives similar results. The other constructors work just fine; it must be the angle that's going wrong here. Whatever result it is I'm getting, it seems to have an inverse relationship with the actual angle, but it's not linear.
I'm at my wits end trying to figure this out; the other constructors calculate arcs from the angle and power and from a target and a given angle (so calculated power) - both these work just fine (the drawn debug arcs in the images are from sweeping sphere casts along the arcs, hence the red Xs when it hits something; either way the GetPoint(float time) function works as it should and is extremely simple). Can anyone help?
The X from Vector2 target, is the distance between the target and the shooter? In a 3D perspective
It's been written for a 2D context, so the x value is the horizontal distance, yes.
Note this is not the literal distance; that would be the magnitude of the vector (x,y).
For a 3D context, you'd want to calculate the arc in two dimensions along the axis [start -> target], then convert to Vector3 and rotate via $$anonymous$$atrix or Quaternions to be in world 3D coordinates.
Answer by TehJustice · Dec 12, 2013 at 08:58 PM
Looks like an order of operations error, your denominator needs to be (g*x) instead of g*x.
...
Yep, that was exactly it. Damnit and I'd thought I'd tried all the possible bracket combinations too. Please excuse me whilst I find a bag in which to scream...