# AI 2D angle based autoaim, how?

I have AI cannon in 2D game and i want it to shoot (left) the player. With constant speed and weight of bullet i need to calculate the angle of cannon barrel to hit the player.
This is my code for now

``````var projectile : Rigidbody; //bullet with weight
private var Distance : float; //Distance between cannon and player
var Target : Transform; //coordinates of player
var attackRange = 15.0; //when the player is closer than "attackRange" try to shoot him
var speed : float = 20; //speed of bullet
var fireRate = 1; //fire rate..

private var nextFireTime = 0.0;

function Update ()
{
Distance = Vector3.Distance(Target.position, transform.position);

if (Distance < attackRange)
{
Fire ();
}
}

function Fire () {

if (Time.time - fireRate > nextFireTime)
nextFireTime = Time.time - Time.deltaTime;

while( nextFireTime < Time.time) {

FireOneShot();
nextFireTime += fireRate;
}
}

function FireOneShot () {
var instantiatedProjectile : Rigidbody = Instantiate( projectile, transform.position, transform.rotation );
instantiatedProjectile.velocity = transform.TransformDirection( Vector3( -speed, 0, 0));
Physics.IgnoreCollision( instantiatedProjectile.collider, transform.root.collider);
}
``````

Cannon just shooting without aiming and i do not know what to do next(
Thank you.

Thank you.
This is my code for now and it`s works fine.

``````var Target: Transform;
var fireRate = 10;
var attackRange = 20.0;

private var Distance : float;
private var nextFireTime = 0.0;

function Update(){

Distance = Vector3.Distance(Target.position, transform.position);
if (Distance < attackRange)
{
Fire ();
}
}

function BallisticVel(Target: Transform, angle: float): Vector3 {
var dir = Target.position - transform.position;  // get target direction
var h = dir.y;  // get height difference
dir.y = 0;  // retain only the horizontal direction
var dist = dir.magnitude ;  // get horizontal distance
dir.y = dist * Mathf.Tan(a);  // set dir to the elevation angle
dist += h / Mathf.Tan(a);  // correct for small height differences
// calculate the velocity magnitude
var vel = Mathf.Sqrt(dist * Physics.gravity.magnitude / Mathf.Sin(2 * a));
return vel * dir.normalized;
}

function ElevationAngle(Target: Transform): float {
// find the cannon->target vector:
var dir = Target.position - transform.position;
// create a horizontal version of it:
var dirH = Vector3(dir.x, 0, dir.y);
// measure the unsigned angle between them:
var ang = Vector3.Angle(dir, dirH);
// add the signal (negative is below the cannon):
return ang;
}

function Fire () {

if (Time.time - fireRate > nextFireTime)
nextFireTime = Time.time - Time.deltaTime;

while( nextFireTime < Time.time) {

FireOneShot();
nextFireTime += fireRate;
}
}

function FireOneShot () {
var ang = ElevationAngle(Target);
var shootAng = ang +15;
transform.eulerAngles.z = -shootAng; //just transform my turret with "shooting angle"