Jordaaaay
Jordaaaay

Reputation: 11

Why does my turret stop shooting AI player?

Currently working on something for my midterms but I'm stuck at one particular part.The AI character has to follow a path using way points and then stop on top of a circle to shoot (destroy) a wall to get to the final waypoint. The AI character has to do this before the Turret located near by shoots and destroys it. The AI character has 3 points of health and dies if shot three times. The Turret has a cool down after every shot so it gives the AI character time to shoot down the wall.

The part that I am stuck at is when the AI character reaches the waypoint to shoot down the wall (Which I haven't implemented yet) The Turret shoots once and doesn't shoot anymore. However, the raycast is working because it looks at the AI as long as it is in range.

Here is my turret Script:

using UnityEngine;
using System.Collections;

public class TurretScript : MonoBehaviour {
public float rangeToPlayer;
public GameObject bullet;
public GameObject spawn;
private GameObject player;
private bool firing = false;
private float fireTime;
private float coolDown = 0.5F;

void Start () {
    player = GameObject.FindWithTag("Player");
}

void Update () {
    if ( PlayerInRange() ) {
        transform.LookAt(player.transform.position);
        RaycastHit hit;
        if( Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit )) {
            Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 20.0F, Color.red);
            if (hit.transform.gameObject.tag == "Player") {
                if ( firing == false )
                {       
                    firing = true;
                    fireTime = Time.time;
                    GameObject.Instantiate(bullet, spawn.transform.position, transform.rotation);
                }
            }
        }
    }
    if ( firing && fireTime + coolDown <= Time.time )
        firing = true;
}

bool PlayerInRange() {
    return ( Vector3.Distance(player.transform.position, transform.position) <= rangeToPlayer );
}
}

Upvotes: 1

Views: 67

Answers (1)

j0ffe
j0ffe

Reputation: 631

You have to set the "firing" variable back to false after cooldown is over. Also suggest that you don't perform the Raycast when the cooldown is in progress to save some CPU.

Upvotes: 2

Related Questions