# make AI shoot at incoming bullet

Hey, I’m creating a little game that plays somewhat like Tanks on Wii Play.

I’m trying to make my AI shoot at bullets if it detects it will hit them. To do this I check on the bullet if it will hit an enemy within a few seconds. Then if this bullet gets detected by the enemy’s ‘vision’, it changes the angle of the cabin and shoots.

This piece of code is part of the ‘Vision’ child. Vision is a child of ‘Cabin’, which is a child of the tank.

``````void OnTriggerEnter(Collider collision)
{
if (collision.GetComponent<BulletScript>().willHit == true)
{
transform.parent.rotation = Quaternion.Euler(0, -90 + transform.parent.rotation.y + (float)Vector3.Angle(transform.forward, (GetComponentInParent<Transform>().transform.position - collision.transform.position)), 0);
transform.parent.GetComponent<Scanner>().Shoot();
}
}
``````

For some reason, the rotation is sometimes off by a few degrees. After it rotated, the collision gets detected again and it snaps immediately back to what it was before. Also, most of the time the counter bullet doesn’t get shot.

Does anyone have a clue what I’m doing wrong?

Are you sure this portion is correct:

``````(float)Vector3.Angle(transform.forward, (GetComponentInParent<Transform>().transform.position
``````

Perhaps it should be:

``````(float)Vector3.Angle(transform.parent.forward, transform.parent.position
``````

You might also clean up the rotation by using LookAt (since apparently you aren’t lerping to the rotation anyways)… This will work if your forward direction is the same as your “expected direction” If it’s not I’d suggest using a parent to correctly align it.

``````transform.parent.rotation.LookAt(new Vector3(collision.transform.position.x, transform.parent.position.y, collision.transform.position.z);
``````

As for the shooting, use a Debug to see if the function is being called… if it is then you have an unexpected collision happening as your object rotates. If it’s not being called then you have a problem with your willHit script.

I fixed the issue.

Apperantly Angles cannot report negative angles. I fixed it like this:

``````if(collision.transform.tag == "Bullet" && collision.GetComponent<BulletScript>().myShot == false)
{
float angled = (float)Vector3.Angle(collision.transform.position - transform.parent.position, transform.forward);
var cross = Vector3.Cross(collision.transform.position - transform.parent.position, transform.forward);
angled = (cross.y < 0) ? -angled : angled;
if (collision.GetComponent<BulletScript>().willHit == true)
{
transform.parent.rotation = Quaternion.Euler(0, transform.parent.eulerAngles.y - angled, 0);
transform.parent.GetComponent<Scanner>().Shoot();
}
}
``````