Quantcast
Channel: Questions in topic: "enemy"
Viewing all articles
Browse latest Browse all 1488

Topdown: Stop Enemy Rapid Firing

$
0
0
Hey basically I have a hostage rescue game whereby the player must rescue hostages whilst avoiding or eliminating enemies. I am using the A* path algorithm with radius detection for the enemies whereby when the player comes within range of the enemy, the enemy will start moving towards the player and shooting them until the player leaves the radius of the enemy. The only problem is that when the enemy starts firing, instead of firing once every second or two, its auto firing really quickly and only stops when the player comes out of range ( as intended). I was wondering if there was anyway I can implement some sort of delay between each time the Shoot function is called so that only one bullet is instantiated per second (or however long). Thank you. using UnityEngine; using System.Collections; public class EnemyShoot : MonoBehaviour { public Transform BulletPrefab; public Transform MuzzleFlashPrefab; Transform spawn; float fireRate = 0; private float shotCooldown = 1.0f; private bool Seen = false; //Whether the enemy has detected the player. public Transform target; public int EnemyRadius = 10; void Awake () { spawn = transform.FindChild ("spawn"); if (spawn == null) { Debug.LogError("No Spawn"); } } // Use this for initialization void Start () { } // Update is called once per frame void Update () { float distanceFromEnemy = Vector2.Distance (transform.position, target.position); //Returns distance between enemy and player. Debug.Log ("Distance from Enemy: " + distanceFromEnemy); if (distanceFromEnemy < EnemyRadius) { //If player is within enemy radius. Seen = true; Shoot (); } else { //if player walks out of enemy radius. Seen = false; } } void Shoot() { Vector2 spawnPosition = new Vector2 (spawn.position.x, spawn.position.y); Instantiate (BulletPrefab, spawn.position, spawn.rotation); //spawns the bullet prefab at spawn position Transform MuzzleFlashInstance = Instantiate (MuzzleFlashPrefab, spawn.position, spawn.rotation) as Transform; //Using a Cast, instantiate inside transform variable MuzzleFlashInstance.parent = spawn; //sets Instance of Muzzle flash to be a child of the spawn of the bullet. float MuzzleFlashSize = Random.Range (0.4f, 0.9f); //Sets the MuzzleFlash to a random size. MuzzleFlashInstance.localScale = new Vector3 (MuzzleFlashSize, 0.14f, 0); Destroy (MuzzleFlashInstance.gameObject, 0.02f); //Destroys the instance of the MuzzleFlashPrefab after use. .gameObject is used to destroy the transform of an object. } }

Viewing all articles
Browse latest Browse all 1488

Trending Articles