AI Aim and Shoot at a Target

From STEAMwiki
Jump to: navigation, search

This script programs a turret or gun on an AI agent to aim towards a target and shoot when in range.

Set up your objects so that the turret's blue Z axis is pointing along the front of the weapon. You may need to create an empty parent object to use as the "turret" gameobject, since your weapon may not naturally be set up this way. For example:

Turret Setup.png

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TankAimShoot : MonoBehaviour {

    public GameObject turret;
    public Rigidbody shotPrefab;
    public GameObject target;

    private float attackTimer = 5f;
    private float attackRange = 40;
    private Vector3 targetDir =;
    public Transform barrelEnd;

    // Use this for initialization
    void Start () {

    // Update is called once per frame
    void Update () {
        // Check the target direction
        targetDir = target.transform.position - transform.position;

        // rotate turret towards target
        Vector3 turretDirection = target.transform.position - turret.transform.position;
        float step = 5 * Time.deltaTime;
        Vector3 newDir = Vector3.RotateTowards(turret.transform.forward, turretDirection, step, 0.0F);
        //Debug.DrawRay(transform.position, newDir,;
        turret.transform.rotation = Quaternion.LookRotation(newDir);

        // Check if we've attacked recently
        attackTimer -= Time.deltaTime;
        if (attackTimer <= 0)

            // Aim and Spawn Bullet if in range
            if (targetDir.magnitude < attackRange)
                // Debug.Log("Tank firing");
                Rigidbody b = GameObject.Instantiate(shotPrefab, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
                b.AddForce(2000 * b.transform.forward);

            attackTimer = 5f;