I need help and guidance from you guys.
I try adding " Shoot if in range" to my enemy attack script and it doesn’t seem to be working.
Even though i move my Player to a very far distance, the enemy still able to shoot me.
using UnityEngine;
using System.Collections;
public class EnemyShoot : MonoBehaviour {
public Transform player;
public float range = 10f;
public float bulletImpulse = 1.0f;
public float mistakeRadius;
private bool onRange= false;
public Rigidbody projectile;
void Start()
{
float rand = Random.Range (1.0f, 2.0f);
// 1st timer for shotting
InvokeRepeating("Shoot", 5, rand);
}
void Shoot()
{
int randomPick = Mathf.Abs (Random.Range (1, 3));
if (onRange)
{
if (randomPick == 1)
{
Rigidbody bullet = (Rigidbody)Instantiate(projectile, transform.position + transform.forward, transform.rotation);
//bullet.AddForce (transform.forward * bulletImpulse, ForceMode.Impulse);
var desiredDirection = (player.position - transform.position) + Random.onUnitSphere;
bullet.AddForce(desiredDirection * bulletImpulse, ForceMode.Impulse);
Destroy (bullet.gameObject, 2);
}
if (randomPick == 2)
{
Rigidbody bullet = (Rigidbody)Instantiate(projectile, transform.position + transform.forward, transform.rotation);
var desiredDirection = (player.position - transform.position) + (Random.onUnitSphere * mistakeRadius);
bullet.AddForce(desiredDirection * bulletImpulse, ForceMode.Impulse);
Destroy (bullet.gameObject, 2);
}
}
}
void Update()
{
onRange = Vector3.Distance(transform.position, player.position) < range;
if (onRange)
{
transform.LookAt (player);
}
}
}